[英]SQL Query for selecting multiple rows but highest value for each PK
I know that the title sounds horrible but I have no idea how to summarize it better.我知道标题听起来很可怕,但我不知道如何更好地总结它。 I'm pretty sure that somebody had the same problem before but I couldn't find anything.
我很确定之前有人遇到过同样的问题,但我找不到任何东西。 RDBMS: MySQL.
关系型数据库:MySQL。
Problem: I have the following (simplified) table:问题:我有以下(简化)表:
+------+------------+---------------------------------+
| name | date | score |
+------+------------+---------------------------------+
| A | 01.01.2015 | 1 |
| A | 01.02.2015 | 3 |
| A | 01.03.2015 | 4 |
| B | 01.01.2015 | 3 |
| B | 01.02.2015 | 4 |
| B | 01.03.2015 | 5 |
| C | 01.01.2015 | 1 |
| C | 01.02.2015 | 2 |
| C | 01.03.2015 | 3 |
+------+------------+---------------------------------+
There is no unique constraint or PK defined.没有定义唯一约束或 PK。
The table represents a highscore of a game.该表代表游戏的最高分。 Every day the score of all players are inserted with values that are: name, points, now(),...
每天,所有玩家的得分都会插入以下值:姓名、分数、now()、...
The data represent a snapshot of the score of each player at a specific time.这些数据代表了每个玩家在特定时间的得分快照。
I want the most recent entry for each user only but only for the highest X players.我只想要每个用户的最新条目,但只想要最高的 X 玩家。 So the result should look like
所以结果应该是这样的
+------+------------+---------------------------------+
| name | date | score |
+------+------------+---------------------------------+
| A | 01.03.2015 | 4 |
| B | 01.03.2015 | 5 |
+------+------------+---------------------------------+
I hope it becomes clear what I mean.我希望我的意思很清楚。
Thanks in advance!提前致谢!
I understand that what you need is to first select the X players who've gotten the highest score and then get their latest performance.我知道你需要先选择得分最高的X个球员,然后再获得他们的最新表现。 In this case, you should do this:
在这种情况下,您应该这样做:
SELECT *
FROM tablename t
JOIN
(
SELECT t.name, max(t.date) as max_date
FROM tablename t
JOIN
(
SELECT name
FROM
(
SELECT name, max(score) as max_score
FROM table_name
GROUP BY name
) all_highscores
ORDER BY max_score DESC
LIMIT X
) top_scores
ON top_scores.name = t.name
GROUP BY t.name
) top_last
on t.name = top_last.name
and t.date = top_last.date;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.