如果我有一个名为“分数”的表,如下所示:
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
如果我有一个名为“分数”的表,如下所示:
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
以下 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
这可以通过以下方式完成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
将我的代码中的字段和表格替换为您的。
;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