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