选择联接的第一个匹配项

时间:2014-02-19 19:59:28

标签: sql-server-2008

所以我有一个SQL语句,它返回如下内容:

PLAYER_ID | PLAYER_NAME | POSITION | 
1           player1       hitter
1           player1       short stop
1           player1       pitcher
2           player2       pitcher
2           player2       catcher

这是通过玩家和current_player_stats之间的内部联接来完成的。

SELECT P.PLAYER_ID, P.PLAYER_NAME, S.POSITION
FROM PLAYERS AS P
INNER JOIN CURRENT_PLAYER_STATS AS S
ON P.PLAYER_ID = S.PLAYER_ID
WHERE P.PLAYER_ID = <some player id>

我可以用什么SQL来过滤这个结果集给我:

PLAYER_ID | PLAYER_NAME | POSITION | 
1           player1       hitter
2           player2       pitcher

即。每个球员的最上一行。

1 个答案:

答案 0 :(得分:2)

如果提供的信息有限,请尝试

;WITH Vals AS (
    SELECT    Player_ID, 
              Player_Name, 
              Position, 
              ROW_NUMBER() OVER(PARTITION BY Player_ID ORDER BY [Columns Here]) as RowID
    FROM YourTable
)
SELECT *
FROM Vals 
WHERE RowID = 1