如何在T-SQL中过滤嵌套查询

时间:2011-08-12 18:54:23

标签: sql-server tsql

我有以下情况:

  • GameGameUID, GameName
  • PlayerPlayerUID, PlayerName
  • GamePlayerGamePlayerUID, GameUID, PlayerUID, FinishedPosition

我需要为每个游戏行返回这三个表之间的一行连接,其中返回行包含具有最低完成位置的Player行。

实施例,

游戏

{some guid}, Game 1
{some guid}, Game 2
{some guid}, Game 3

播放器

{some guid}, Player 1
{some guid}, Player 2

的游戏玩家

{some guid}, {game 1 guid}, {player 1 guid}, 1
{some guid}, {game 1 guid}, {player 2 guid}, 2
{some guid}, {game 2 guid}, {player 1 guid}, 2
{some guid}, {game 2 guid}, {player 2 guid}, 1

我的预期结果是

Result
-------
{game 1 guid}, Game 1, {player 1 guid}, Player 1
{game 2 guid}, Game 2, {player 2 guid}, Player 2

现在我的直觉告诉我这应该是查询:

select G.GameUID, G.GameName, V.PlayerUID, P.PlayerName
from Game G inner join (
    select top(1) GameUID, PlayerUID 
    from GamePlayer GP
    where GP.GameUID = G.GameUID
    order by FinishedPosition asc) as V on V.GameUID = G.GameUID
inner join Player P on V.PlayerUID = P.PlayerUID

现在,此查询的问题是where GP.GameUID = G.GameUID会产生

  

多部分标识符“G.GameUID”无法绑定

错误。

如果我将其排除并仅依赖于连接条件,则子查询始终具有相同的第一行,因此它只会加入其中一个游戏。

我希望我已经明确地说明了某人提供答案。

顺便说一句,这是放在一个视图中。除非绝对必要,否则我不想编写存储过程来执行此操作。

1 个答案:

答案 0 :(得分:2)

select G.GameUID, G.GameName, P.PlayerUID, P.PlayerName
from Game G inner join (
    select GameUID, MIN(FinishedPosition) as FinishedPosition
    from GamePlayer GP
    group by GP.GameUID) as V on V.GameUID = G.GameUID
inner join GamePlayer GP2 on (GP2.FinishedPosition = V.FinishedPosition and GP2.GameUID = V.GameUID)
inner join Player P on (P.PlayerUID = GP2.PlayerUID)

呼。我觉得那样呢?如果它失败了,请告诉我。