Include an additional counter in the MySQL result set

a 夏天 提交于 2019-12-30 07:02:55

问题


Can I include an additional counter in a MySQL result set? I have the following query which gives me two columns back. I need an additional column (only in the result) indicating the row of each line in the result set.

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

I need something like the following:

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

回答1:


Try this:

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



回答2:


Try following

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

Hope it helps...




回答3:


Based on the two answers I managed to get the following:

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

The original answers showed the IDs from the inner query resulting in larger ints with huge gaps. Using the modification I get just the '1 to x' range that I need for my pgfplots LaTeX plot.



来源:https://stackoverflow.com/questions/12769415/include-an-additional-counter-in-the-mysql-result-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!