SQL面试题:在t_score
表中,找到表中每个人最近的一条分数
username | score | time |
---|---|---|
小明 | 98 | 2021-07-29 |
小明 | 90 | 2021-07-01 |
小红 | 96 | 2021-07-15 |
小红 | 100 | 2021-06-21 |
小李 | 95 | 2021-05-03 |
结果就应该是
username | score | time |
---|---|---|
小明 | 98 | 2021-07-29 |
小红 | 96 | 2021-07-15 |
小李 | 95 | 2021-05-03 |
两种解法:
双表联查
SELECT t1.* FROM t_score t1
INNER JOIN (SELECT username, MAX(time) AS time FROM t_score GROUP BY username) t2
ON t1.username = t2.username AND t1.time = t2.time
开窗函数(MySQL不支持)
SELECT * FROM (
SELECT *, row_number() over (partition by username order by time desc) AS rn FROM t_score
) WHERE rn = 1