2009-12-18 73 views
0

我試圖內加入2個臨時表
我知道這是可以做到的,我以前做過,但我完全忘了該怎麼辦呢


告訴我下面是,我試圖執行

幫助與SQL 2005和內部連接

select tmp1.*, tmp2.cnt from 
(
    select 
     1 as ClassificationType, 
     tblMatches.IdGame, 
     tblMatches.IdPlayer, 
     sum(Score) as Score, sum(Points) as Points, sum(OpponentScore) as OpponentScore, 
     count(ID) as MatchesCount, count(distinct IdCompetition) as CompetitionsCount 
    from 
     tblMatches 
    group by IdPlayer, IdGame 
) as tmp1 
inner join (select IdWinner, count(IdWinner) as cnt from tblCompetitions where IdWinner = tmp1.IdPlayer) as tmp2 
      on tmp2.IdWinner = tmp1.IdPlayer 

這將失敗,並
我想我不允許在創建TMP2

01子查詢中使用TMP1查詢

Msg 4104,Level 16,State 1,Line 17 多部分標識符 「tmp1.IdPlayer」無法綁定。

回答

3

您不是想要連接兩個臨時表,而是兩個派生表。

除非它在SELECT子句中,否則無法訪問其外部的一個派生表的內部數據。

嘗試以下操作:

select tmp1.*, tmp2.cnt from 
(
    select 
     1 as ClassificationType, 
     tblMatches.IdGame, 
     tblMatches.IdPlayer, 
     sum(Score) as Score, sum(Points) as Points, sum(OpponentScore) as OpponentScore, 
     count(ID) as MatchesCount, count(distinct IdCompetition) as CompetitionsCount 
    from 
     tblMatches  
    group by IdPlayer, IdGame 
) as tmp1 
inner join (select IdWinner, count(IdWinner) as cnt from tblCompetitions GROUP BY IdWinner) as tmp2 
       on tmp2.IdWinner = tmp1.IdPlayer 
1

的其中tmp2條款複製連接條件:

inner join (select IdWinner, count(IdWinner) as cnt 
      from tblCompetitions 
      where IdWinner = tmp1.IdPlayer) as tmp2 
on   tmp2.IdWinner = tmp1.IdPlayer 

只需卸下where條款。此外,像Astander他現在刪除的文章中指出,第二查詢需要group by太:

inner join (select IdWinner, count(IdWinner) as cnt 
      from tblCompetitions 
      group by IdWinner) as tmp2 
on   tmp2.IdWinner = tmp1.IdPlayer 

你不能從一個子查詢引用外部查詢的原因是,這將使的右部連接取決於連接的左側部分。

1

你實際上不需要第二個子查詢。那這個呢?

SELECT tmp1.ClassificationType, tmp1.IdGame, tmp1.IdPlayer, 
     COUNT(tblCompletions.IdWinner) as cnt FROM 
(
    SELECT 
     1 as ClassificationType, 
     tblMatches.IdGame, 
     tblMatches.IdPlayer, 
     sum(Score) as Score, sum(Points) as Points, sum(OpponentScore) as OpponentScore, 
     count(ID) as MatchesCount, count(distinct IdCompetition) as CompetitionsCount 
    FROM 
     tblMatches  
    GROUP BY IdPlayer, IdGame 
) as tmp1 
INNER JOIN tblCompletions ON tmp1.IdPlayer = tblCompletions.IdWinner 
GROUP BY tmp1.ClassificationType, tmp1.IdGame, tmp1.IdPlayer 
2
select 
    1 as ClassificationType, 
    tmp1.IdGame, 
    tmp1.IdPlayer, 
    sum(tmp1.Score) as Score, 
    sum(tmp1.Points) as Points, 
    sum(tmp1.OpponentScore) as OpponentScore, 
    count(tmp1.ID) as MatchesCount, 
    count(distinct tmp1.IdCompetition) as CompetitionsCount, 
    count(tmp2.IdWinner) as cnt 
from 
    tblMatches tmp1 
    inner join 
    tblCompetitions tmp2 
     on tmp2.IdWinner = tmp1.IdPlayer 
group by 
    tmp1.IdPlayer, 
    tmp1.IdGame