4

我可以在 MySQL 结果集中包含一个额外的计数器吗?我有以下查询,它给了我两列。我需要一个额外的列(仅在结果中),指示结果集中每一行的行。

select orderid, round(sum(unitprice * quantity),2) as value
from order_details
group by orderid
order by 2 desc
limit 10

我需要以下内容:

10865 1 17250.00
11030 2 16321.90
10981 3 15810.00
10372 4 12281.20
10424 5 11493.20
4

3 回答 3

10

尝试这个:

SET @counter = 0; 
Select sub.*
FROM
(
    select orderid, (@counter := @counter +1) as counter,
      round(sum(unitprice * quantity),2) as value
    from order_details
    group by orderid
) sub
order by 2 desc
于 2012-10-07T13:55:32.457 回答
5

尝试关注

SET @counter = 0;
select orderid, (@counter:= @counter + 1) as counter, round(sum(unitprice * quantity),2) as value
from order_details
group by orderid
order by 3 desc
limit 10

希望能帮助到你...

于 2012-10-07T13:55:47.643 回答
0

基于这两个答案,我设法得到以下信息:

SET @counter = 0; 

Select sub.orderid,sub.value,(@counter := @counter +1) as counter
FROM
(
    select orderid, 
      round(sum(unitprice * quantity),2) as value
    from order_details
    group by orderid
) sub
order by 2 desc
limit 10

原始答案显示来自内部查询的 ID 导致更大的整数和巨大的差距。使用修改,我得到了我的 pgfplots LaTeX 绘图所需的“1 到 x”范围。

于 2012-10-07T20:16:39.703 回答