2010-08-11 145 views

回答

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 
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

如何

SELECT MAX(Id), userId, Score 
FROM table 
GROUP BY UserId 
+0

錯誤 - 「分數」不在聚合中或聚合內。也不保證'id'和'score'值是連接的。 – 2010-08-11 14:44:46

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 
相關問題