[英]Select max value AND the corresponding row id grouped by date
我有一个(mssql)排名表,它有一个id 、一个username 、一个date和一个score属性。
id | username | date | score
----------------------------
1 joe 01/2020 200
2 bob 01/2020 300
3 max 02/2020 350
4 jane 02/2020 300
5 bob 02/2020 250
6 joe 03/2020 150
我想要实现的是 select 按日期分组的最高分数与相应的 id 和用户名,这将产生如下结果:
id | username | date | score
----------------------------
2 bob 01/2020 300
3 max 02/2020 350
6 joe 03/2020 150
我绝不是数据库专家,我失败得很惨!
有人可以帮我弄这个吗? 谢谢!
编辑:此时我不在乎关系。
如果您的数据库支持 window 函数:
Select * from (Select t.*,
row_number() OVER (Partition by date order by score desc) rn
from table t) where rn = 1;
+----+----------+---------+-------+----+
| id | username | dte | score | rn |
+----+----------+---------+-------+----+
| 2 | bob | 01/2020 | 300 | 1 |
+----+----------+---------+-------+----+
| 3 | max | 02/2020 | 350 | 1 |
+----+----------+---------+-------+----+
| 6 | joe | 03/2020 | 150 | 1 |
+----+----------+---------+-------+----+
尝试如下
select a.* form table_name a
where a.score=( select max(score) from table_name b where a.date=b.date )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.