2015-04-03 31 views
1

我在這個樣本格式數據:從遊戲/得分數據返回獲獎名單 - SQL Server 2012的

 
name  score game# 
----- ----- ----- 
PlayerA 100  1 
PlayerB 50  1 
PlayerC 75  2 
PlayerD 150  2 
PlayerE 100  3 

等。我想列出下列「獲獎者」名單:

 
game# winner  score 
----- -----  ----- 
1  PlayerA 100 
2  PlayerD 150 
3  .....  ... 

有什麼建議嗎?我在摸索着使用MAX和GROUP BY,而沒有獲得所有我想要的列。感謝大家!

回答

2

聽起來像是ranking的情況下,因此,或許一些有點像:

;WITH ranked AS (
    SELECT  RANK() OVER (PARTITION BY [Game#] ORDER BY Score DESC) AS Position, 
       Name, 
       Score, 
       [Game#] 

    FROM  Results 
) 
SELECT  [Game#], 
      Name AS Winner, 
      Score 

FROM  ranked  

WHERE  ranked.Position = 1 
+0

這很漂亮! – Yoav24 2015-04-03 07:21:15

0

僅僅通過遊戲數組,計算max(score)然後加入結果回來原來的表來獲得具有設置在每場比賽最高分的球員:

select 
    T.game, 
    T1.name as winner, 
    T.score 
from 
    (
     select 
      game, 
      max(score) as score 
     from Your_Table 
     group by game 
    ) as T 
    left outer join Your_Table as T1 on T1.game = T.game and T1.score = T.score 
+0

我會嘗試這樣的事情 - 即時通訊不是很好,但這是我一直在尋找我認爲!儘管其他用戶的排名榜樣也很好。 – Yoav24 2015-04-03 07:20:40