mysql 成绩排名 字段_MySQL 对某个字段先统计后获取排序名次

一,普通获取排序名次

比如获取一个班级成绩排名,分两步

(1)查出所有用户和他们的成绩排名

select id,maxScore,(@rowNum:=@rowNum+1) as rowNo

from t_user,

(select (@rowNum :=0) ) b

order by t_user.maxScore desc

(2)查出某个用户在所有用户成绩中的排名

select u.rowNo from (

select id,(@rowNum:=@rowNum+1) as rowNo

from t_user,

(select (@rowNum :=0) ) b

order by t_user.maxScore desc ) u where u.id="2015091810371700001";

二,那假如是统计某个字段总数再排名呢,如场景:

直播间里,观众给主播打赏的时候,主播可以收益货币,每次打赏都会记录在A表。

A表:fuid(发起者) uid(收益者) ctime(创建时间戳) coin(货币)

现在使用sql语句获取收益者B的本周收益的排名名次。(不使用循环)

也是分两步,第一步,将货币字段先排序好,再获取某个单独用户的排序名次

(1)获取统计字段整体排序

select uid,sum(coin) as total,(@rowNum:=@rowNum+1) as rowNo

from money,

(select (@rowNum :=0) ) b

where ctime BETWEEN '1609498844' and '1610103956'

GROUP BY money.uid

order by total desc

(2)获取排序好的名次字段

select m.rowNo from (select uid,sum(coin) as total,(@rowNum:=@rowNum+1) as rowNo

from money,

(select (@rowNum :=0) ) b

where ctime BETWEEN '1609498844' and '1610103956'

GROUP BY money.uid

order by total desc) m where m.uid =102;

直接上图:

表数据:

16ad5c36350af2757971f3345991110f.png

第一次查询结果:

164f084177f0e75adef6dfd660d2f46b.png

第二次直接获取里面的字段就好了


版权声明:本文为weixin_30382087原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。