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;
执行结果:
sid | score | row_num | cid2 |
---|---|---|---|
李四 | 99 | 1.0 | cid-01 |
张三 | 78 | 2.0 | cid-01 |
小明 | 90 | 3.0 | cid-01 |
李四 | 94 | 1.0 | cid-02 |
张三 | 66 | 2.0 | cid-02 |
小明 | 67 | 3.0 | cid-02 |
李四 | 90 | 1.0 | cid-03 |
张三 | 55 | 2.0 | cid-03 |
小明 | 88 | 3.0 | cid-03 |