帮助SQL 2005和内部联接

时间:2009-12-18 15:57:23

标签: sql-server inner-join

我正在尝试内连接2个临时表
我知道这可以做到,我之前做过这件事,但我完全忘了怎么做了
请告诉我以下是我尝试执行的查询

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的子查询中使用tmp1

  

Msg 4104,Level 16,State 1,Line 17   多部分标识符   “tmp1.IdPlayer”无法绑定。

4 个答案:

答案 0 :(得分: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 :(得分: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

答案 2 :(得分:1)

tmp2中的where子句重复了连接条件:

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

您无法从子查询引用外部查询的原因是,这会使连接的正确部分取决于连接的左侧部分。

答案 3 :(得分: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