我有UserScores表,其数据如下:
Id userId Score
1 1 10
2 2 5
3 1 5
我想有一个查询或SQL块可以给我以下输出
Id userId Score
3 1 5
2 2 5
也就是说,我想选择属于最高'id'列值的'user id'唯一的行。
答案 0 :(得分:3)
另一种适用于SQL Server 2000的解决方案(与上面的INNER JOIN相同,但速度稍快)是:
SELECT id, userId, Score
FROM UserScores
WHERE id in (SELECT MAX(id)
FROM UserScores
GROUP BY userId
)
ORDER BY userId
答案 1 :(得分:2)
使用:
WITH summary AS (
SELECT t.id,
t.userid,
t.score,
ROW_NUMBER() OVER (PARTITION BY t.userid ORDER BY t.id DESC, t.score DESC) AS rank
FROM USERSCORES sc)
SELECT s.id,
s.userid,
s.score
FROM summary s
WHERE s.rank = 1
答案 2 :(得分:2)
怎么样
SELECT MAX(Id), userId, Score
FROM table
GROUP BY UserId
答案 3 :(得分:1)
SELECT U2.id, U2.userId, U2.score
FROM UserScores U2
INNER JOIN (
SELECT U1.userId, MAX(U1.Id) MaxId
FROM UserScores U1
GROUP BY U1.userId
) U3
ON U2.id = U3.MaxId and U2.userId = U3.userId
ORDER BY U2.userId