在mysql

时间:2016-04-19 04:25:43

标签: mysql rank

我有一个Mysql查询,我试图对一列进行求和,并按总数排名。

这是我的问题:

select 
@rownum:=@rownum+1 as rank,
sum(length) as total,
user_id
from submissions,
(select @rownum:=0) a WHERE id = 1067 AND status = 1
group by user_id
 order by total desc

这导致:

rank    total    user_id    
 2      65.25     1360
 1      59.50     1151
 4      58.00     1250
 6      55.75     1374
 5      51.25     1154
 3      34.75      841

1 个答案:

答案 0 :(得分:0)

我认为你必须首先使用内部查询来获取总数,然后使用这样的外部选择对它们进行排名:

select @rownum:=@rownum+1 as rank,
       total,
       user_id
from 
    (select sum(length) as total,
            user_id
     from submissions
     WHERE id = 1067 AND status = 1
     group by user_id
     order by total desc)T,(select @rownum:=0)a