Cong BJP AAP Winner Win By 25554 36985 **26929** BJP 10056 19753 **24569** 36239 AAP 11670
使用Sql server 2008,这是一个投票表,我想从Cong,BJP和AAP列中选择第二个最大投票数,其中列名为结果值 回报 预期结果:
Againstvote AgainstPartyName 26929 AAP 24569 BJP
答案 0 :(得分:0)
select
case
when BJP between AAP and Cong then BJP
when AAP between BJP and Cong then AAP
else Cong
end as AgainstVote,
case
when BJP between AAP and Cong then 'BJP'
when AAP between BJP and Cong then 'AAP'
else 'Cong'
end as AgainstPartyName
from tab
答案 1 :(得分:0)
您似乎想要一种方法将列名称视为数据的一部分。我会说,这说的是次优设计。无论如何,在你的特殊情况下,有救援的UNPIVOT条款:
SELECT
Votes AS AgainstVotes,
PartyName AS AgainstPartyName
FROM dbo.atable AS t
UNPIVOT (
Votes FOR PartyName in (BJP, AAP)
) AS u
WHERE PartyName <> Winner
;
UNPIVOT子句将您的数据集转换为:
Cong PartyName Votes Winner Win By
----- --------- ----- ------ ------
25554 BJP 36985 BJP 10056
25554 AAP 26929 BJP 10056
19753 AAP 36239 AAP 11670
19753 BJP 24569 AAP 11670
WHERE子句然后过滤掉获胜选票的行,使参与者丢失。