我想获得每位用户每场比赛的最新高分。我当前的查询无效。
我有一个类似以下的SQL DB:
player(string) game(string) score(int) Date(Date) time(Time)
jake soccer 20 2016/02/26 10:00:00
jake chess 50 2016/02/26 10:00:00
jake soccer 40 2016/02/26 13:00:00
jake chess 30 2016/02/26 13:00:00
jake soccer 20 2016/02/26 15:00:00
jake chess 60 2016/02/26 15:00:00
jake soccer 80 2016/02/26 18:00:00
jake chess 10 2016/02/26 18:00:00
mike chess 30 2016/02/26 13:00:00
mike soccer 20 2016/02/26 15:00:00
mike chess 60 2016/02/26 15:00:00
mike soccer 80 2016/02/26 18:00:00
mike chess 10 2016/02/26 18:00:00
我想要摆脱的是:
jake soccer 80 2016/02/26 18:00:00
jake chess 10 2016/02/26 18:00:00
mike soccer 80 2016/02/26 18:00:00
mike chess 10 2016/02/26 18:00:00
我发现时间列也有日期,所以这应该有效。 这是我目前的查询:
SELECT t1.*
FROM db t1
INNER JOIN (
SELECT player, MAX(time) TS
FROM db
GROUP BY player
) t2 ON t2.player = t1.player and t2.TS = t1.time
ORDER BY score DESC";
编辑:我收到了很多错误的行。基本上。我按时间排序,但不按日期排序
我现在需要不仅按MAX(时间)而且按MAX(日期)对它们进行排序。或者在新var中合并日期和时间
答案 0 :(得分:1)
要获得每位用户的最新高分,请尝试以下操作:
;WITH cte as (
SELECT player, game, MAX(convert(datetime,cast([date] as nvarchar(10)) + ' '+ cast([time] as nvarchar(10)))) TS
FROM db
GROUP BY player, game)
SELECT db.*
FROM cte
LEFT JOIN db ON cte.player = db.player and cte.game = db.game and cte.TS = convert(datetime,cast(db.[date] as nvarchar(10)) + ' '+ cast(db.[time] as nvarchar(10)))
ORDER BY highscore DESC
答案 1 :(得分:1)
尝试使用ROW_NUMBER()
SELECT
t1.*
FROM (
SELECT
*
, ROW_NUMBER() OVER (PARTITION BY player ORDER BY [time] DESC) AS rn
FROM db
) AS t1
WHERE rn = 1
;
答案 2 :(得分:0)
由于您不仅需要最新的游戏,还需要其得分,因此此问题可以使用此处讨论的相同模式:Select first row in each GROUP BY group?
就我个人而言,我认为选择最新的time
然后使用它来匹配外部查询中的行是有点可怕的,因为有人可能在同一时刻有两个游戏。它也不会给你最好的表现。根据您的RDBMS,链接的问题可能有更好的方法。