针对5.7.3的版本,文章一定要看"注意点"
部分
一、分组排序
实现如下功能:row_number()over(partition by A order by B)
1、场景描述:每门课程按照分数升序排序。
SELECT
a.sid ,
a.score,
-- a.cid , 不能有该字段,添加该字段,不能分组排序,是全局排序
( @rank := CASE WHEN @cid = a.cid THEN @rank + 1 ELSE 1 END ) AS row_num,
( @cid := a.cid ) AS cid2
-- 字段中必须有字段逻辑 ( @cid := a.cid ),否则不能实现分组排序;且分组字段必须在排序字段后面,否则是针对所有数据排序
FROM
(select
*
from
(
-- sid :学升;cid :课程编码; score :成绩
select '小明' sid,'cid-01' cid, 90 score union all
select '小明' sid,'cid-02' cid, 67 score union all
select '小明' sid,'cid-03' cid, 88 score union all
select '张三' sid,'cid-01' cid, 78 score union all
select '张三' sid,'cid-02' cid, 66 score union all
select '张三' sid,'cid-03' cid, 55 score union all
select '李四' sid,'cid-01' cid, 99 score union all
select '李四' sid,'cid-02' cid, 94 score union all
select '李四' sid,'cid-03' cid, 90 score
)t
ORDER BY cid, sid DESC
) as a
INNER JOIN ( SELECT @rank := 0, @cid := 0 ) AS b ON 1 =1
注意(重点!!!!):
select中必须有字段逻辑( @cid := a.cid ),否则不能实现分组排序;且分组字段a.cid 、@cid := a.cid
必须在排序字段后面,否则是针对所有数据排序
二、全局排序
实现如下功能:row_number()over(order by B)
1、场景描述:按照月份倒序
select
date_month
,months
,@rank:= @rank+1 rn -- 排序
from
(select
t.*
from
(select '2022-08' date_month,'8月' months union all
select '2022-09' date_month,'9月' months union all
select '2022-03' date_month,'3月' months union all
select '2022-04' date_month,'4月' months union all
select '2022-05' date_month,'5月' months union all
select '2022-06' date_month,'6月' months union all
select '2022-07' date_month,'7月' months union all
select '2022-01' date_month,'1月' months union all
select '2022-02' date_month,'2月' months
)t
order by date_month desc)a,( SELECT @rank := 0, @cid := 0 ) b
网友评论