stronger-xsw

一,普通获取排序名次
比如获取一个班级成绩排名,分两步
(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;

直接上图:
表数据:

第一次查询结果:

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

分类:

技术点:

相关文章:

  • 2021-09-07
  • 2021-12-24
  • 2021-12-31
  • 2022-01-30
  • 2021-12-23
  • 2022-01-01
  • 2022-12-23
  • 2022-01-13
猜你喜欢
  • 2021-12-27
  • 2022-12-23
  • 2022-12-23
  • 2021-11-05
  • 2021-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案