如果我有一个名为“得分”的单一表:
PLAYER DATE SCORE
joe 3/1/13 4
joe 3/3/13 5
joe 3/6/13 3
dave 3/3/13 6
dave 3/5/13 8
dave 3/7/13 7
如何查询每位玩家的最新分数?要生成如下结果集:
PLAYER LATEST_SCORE
john 3
dave 7
答案 0 :(得分:2)
以下SQL在给定用户名只能为给定日期生成一个条目的情况下工作。
CREATE TABLE #t1 (
player varchar(max),
dated datetime,
score int
)
insert into #t1 values ('joe', '2013-03-01', 4)
insert into #t1 values ('joe', '2013-03-03', 5)
insert into #t1 values ('joe', '2013-03-06', 3)
insert into #t1 values ('dave', '2013-03-03', 6)
insert into #t1 values ('dave', '2013-03-05', 8)
insert into #t1 values ('dave', '2013-03-07', 7)
SELECT player, score
from #t1 AS t1
WHERE dated = (SELECT MAX(t2.DATED) FROM #t1 AS t2 WHERE t1.player = t2.player)
DROP TABLE #t1
答案 1 :(得分:1)
这可以通过ROW_NUMBER
:
SELECT Player, Date, Score
FROM
(
SELECT Player, Date, Score, Rn = ROW_NUMBER() OVER (PARTITION BY Player ORDER BY Date DESC)
FROM Games
) g
WHERE rn = 1
答案 2 :(得分:0)
用您的代码替换我的代码中的字段和表。
;WITH da_CTE AS (
SELECT
ROW_NUMBER() OVER ( PARTITION BY da_player ORDER BY da_date DESC ) AS 'RowNumber',
da_player,
da_date,
da_score
FROM #s
)
SELECT
da_player,
da_score
FROM da_CTE
WHERE RowNumber =1
ORDER BY da_player