在MySQL结果集中包含一个额外的计数器

时间:2012-10-07 13:53:31

标签: mysql counter calculated-columns

我可以在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

3 个答案:

答案 0 :(得分:9)

试试这个:

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

答案 1 :(得分: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

希望它有所帮助...

答案 2 :(得分: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'范围。