我在本声明中的第二次内部联接有什么问题

时间:2014-02-04 16:29:52

标签: sql-server inner-join

此查询有效:

select  rc.[race number],
    max(case when seqnum = 1 then [candidate num] end) as Winner,
    max(case when seqnum = 1 then Votes end) as WinningVotes,
    max(case when seqnum = 1 then party end) as WinningParty,
    max(case when seqnum = 2 then [candidate num] end) as Loser,
    max(case when seqnum = 2 then Votes end) as LosingVotes,
    max(case when seqnum = 2 then party end) as LosingParty
from 
(
    select  rc.[race number],
            rc.[candidate num],
            rc.[Votes],
            c.[party],
                row_number() over (partition by rc.[race number] order by votes desc) as seqnum
        from    dbo.[RACE CANDIDATES] rc
        inner join dbo.[CANDIDATE] c    on  rc.[candidate num]  = c.[candidate number]
) rc
group by rc.[race number]

现在,我需要从名为RACE的第3个表中加入信息。我尝试了以下查询,但它在第二个内部联接之前的from语句中出错:

select  rc.[race number]
    max(case when seqnum = 1 then [candidate num] end) as Winner,
    max(case when seqnum = 1 then Votes end) as WinningVotes,
    max(case when seqnum = 1 then party end) as WinningParty,
    max(case when seqnum = 2 then [candidate num] end) as Loser,
    max(case when seqnum = 2 then Votes end) as LosingVotes,
    max(case when seqnum = 2 then party end) as LosingParty
from 
(
    select  rc.[race number],
            rc.[candidate num],
            rc.[Votes],
            c.[party],
                row_number() over (partition by rc.[race number] order by votes desc) as seqnum
        from    dbo.[RACE CANDIDATES] rc
        inner join dbo.[CANDIDATE] c    on  rc.[candidate num]  = c.[candidate number]
        from    dbo.[RACE] r
        inner join dbo.[RACE CANDIDATES] on rc.[race number] = r.[race number]          
) rc
group by rc.[race number]

我不确定我在这里做错了什么。这甚至可能吗?我知道我已经在这个特定的查询上发了很多帖子,但我只是想把它弄好。提前感谢您的宝贵帮助。

1 个答案:

答案 0 :(得分:0)

更改查询如下

select  rc.[race number]
    max(case when seqnum = 1 then [candidate num] end) as Winner,
    max(case when seqnum = 1 then Votes end) as WinningVotes,
    max(case when seqnum = 1 then party end) as WinningParty,
    max(case when seqnum = 2 then [candidate num] end) as Loser,
    max(case when seqnum = 2 then Votes end) as LosingVotes,
    max(case when seqnum = 2 then party end) as LosingParty
from 
(
select  rc.[race number],
        rc.[candidate num],
        rc.[Votes],
        c.[party],
            row_number() over (partition by rc.[race number] order by votes desc) as seqnum
    from    dbo.[RACE CANDIDATES] rc
    inner join dbo.[CANDIDATE] c    on  rc.[candidate num]  = c.[candidate number]
    inner join dbo.[RACE] r
     on rc.[race number] = r.[race number]          
) rc
group by rc.[race number]
相关问题