简体   繁体   English

Select 最大值和按日期分组的相应行 id

[英]Select max value AND the corresponding row id grouped by date

I have a (mssql) ranking list table which has an id , a username , a date and a score attribute.我有一个(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

What I'm trying to achieve is to select the highest score grouped by date with the corresponding id and username, which would produce a result like the following:我想要实现的是 select 按日期分组的最高分数与相应的 id 和用户名,这将产生如下结果:

id | username | date | score
----------------------------
2      bob    01/2020  300
3      max    02/2020  350
6      joe    03/2020  150

I'm by no means a database guy and I failed miserably!我绝不是数据库专家,我失败得很惨!

Can someone help me with this?有人可以帮我弄这个吗? Thanks!谢谢!

Edit: I don't care about ties at this point.编辑:此时我不在乎关系。

if your database supports window functions:如果您的数据库支持 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 |
+----+----------+---------+-------+----+

Try like below尝试如下

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM