我已阅读帖子,回答如何在mysql中对结果进行排名,但我的问题是如何在组内分配排名
让我用一个例子来解释
数据:
sem_id | result_month
--------------------
1 |1313907325000
1 |1345529725000
2 |1329804925000
2 |1361427325000
3 |1377065725000
3 |1440137725000
使用以下查询我能够实现的目标:
SELECT @ss := @ss + 1 AS rank,
res.sm_id,
res.result_month
FROM (SELECT sm_id, result_month
FROM xx_table
GROUP BY sm_id,
result_month) AS res,(SELECT @ss := 0) AS ss;
目前的结果:
rank | sem_id | result_month
----------------------------
1 | 1 |1313907325000
2 | 1 |1345529725000
3 | 2 |1329804925000
4 | 2 |1361427325000
5 | 3 |1377065725000
6 | 3 |1440137725000
我真正想要的是什么:
rank | sem_id | result_month
----------------------------
1 | 1 |1345529725000
2 | 1 |1313907325000
1 | 2 |1361427325000
2 | 2 |1329804925000
1 | 3 |1440137725000
2 | 3 |1377065725000
在上述结果中,要观察的是每个组在其自身内排名和每个组按result_month desc排序
帮助我如何实现上述结果
提前致谢!
答案 0 :(得分:1)
你几乎就在那里,使用另一个变量来计算组:
SELECT @ss := CASE WHEN @grp = sem_id THEN @ss + 1 ELSE 1 END AS rank, sem_id, result_month, @grp := sem_id
FROM (select * from xx_table ORDER BY sem_id, result_month DESC) m
CROSS JOIN (SELECT @ss := 0, @grp = null) ss
请在此处查看demo。