这个查询给我带来了我想要的结果。那太好了!
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 = 1 then leader end) as Winner1,
max(case when seqnum = 1 then winner end) as WinnerSelected,
max(case when seqnum = 1 then [leader percent] end) as WinnerPercent,
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,
max(case when seqnum = 2 then leader2 end) as Loser2,
max(case when seqnum = 2 then [leader2 percent] end) as LoserPercent,
max(case when seqnum = 2 then winner end) as LoserSelected
from
(
select rc.[race number],
rc.[candidate num],
rc.[Votes],
rc.[winner],
c.[party],
r.[leader],
r.[leader percent],
r.[leader2],
r.[leader2 percent],
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]
我现在遇到的问题是我在查询中需要在RACE表中有一个title1字段。我无法绑定该多部分标识符。这就是我在论坛上开始寻求和摧毁的原因。
每场比赛都有一个冠军和2个候选人。我试图将两个候选者和领先数据放入一个单行集中。现在,我唯一缺少的是title1字段!哈啊!它永远不会结束。
我认为我不能在最大范围内(案例选择,因为它肯定会重复比赛号码。
我希望这是有道理的。我很抱歉在论坛上浪费了这么多的带宽。
答案 0 :(得分:0)
select rc.[race number] AS RaceNumber,
max(case when seqnum = 1 then title1 end) as title1,
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 = 1 then leader end) as Winner1,
max(case when seqnum = 1 then CAST(winner AS tinyint) end) as WinnerSelected,
max(case when seqnum = 1 then [leader percent] end) as WinnerPercent,
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,
max(case when seqnum = 2 then leader2 end) as Loser2,
max(case when seqnum = 2 then [leader2 percent] end) as LoserPercent,
max(case when seqnum = 2 then CAST(winner AS tinyint) end) as LoserSelected
from
(
select
r.title1,
rc.[race number],
rc.[candidate num],
rc.[Votes],
rc.[winner],
c.[party],
r.[leader],
r.[leader percent],
r.[leader2],
r.[leader2 percent],
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]
我明白了。谢谢大家!!!