我有以下表格结构:
候选:
CandidateId - CandidateName - Symbol
2000 - Hillary - Mobile
2001 - Trumph - Car
2002 - Jackson - Laptop
CastVote:
ID - VotedId - CandidateSymbol
1 - 234BB12344MK23468 - 2000
2 - 234BB12344MK23469 - 2000
2 - 234BB12344MK23470 - 2000
2 - 234BB12344MK23471 - 2002
所以输出如下:
ID - Candidate - Votes - Status
1 - 2000 - 3 - Winner
2 - 2001 - 0 - Loser
3 - 2002 - 1 - Loser
如果任何候选人具有相同的否,则输出可以是这样的。投票:
ID - Candidate - Votes - Status
1 - 2000 - 2 - Winner
2 - 2001 - 0 - Loser
3 - 2002 - 2 - Winner
我使用了以下可以正常运行的查询,但如果候选人没有任何投票,则会将该候选人的投票数返回为1:
ID - Candidate - Votes - Status
1 - 2000 - 2 - Winner
2 - 2001 - 1 - Loser
3 - 2002 - 2 - Winner //Returns 1 even it has no record in the **CastVote** table
使用以下查询:
WITH MyCTE AS (
SELECT k.CandidateName, k.Symbol, COUNT(*) AS Votes
FROM CastVote m
FULL OUTER JOIN Candidate k
ON k.CandidateId = m.CandidateSymbol
GROUP BY CandidateSymbol, k.CandidateName, k.Symbol
)
SELECT Symbol, CandidateName, Votes,CASE
WHEN DENSE_RANK()
OVER (ORDER BY Votes DESC) = 1
THEN 'Winner' ELSE 'Loser' END Status
FROM MyCTE
答案 0 :(得分:1)
公用表表达式确实在这里节省了一天,允许我们取消本来很难看的子查询,以确定每个候选人的status
。很多时候无法处理平局是一个问题,但在你的情况下你可以拥有一个以上的赢家,在这种情况下,我们不必担心有多个候选人的人数最多投票。
WITH Votes_CTE (CandidateSymbol, Votes)
AS
(
SELECT CandidateSymbol, COUNT(*) AS Votes
FROM CastVote
GROUP BY CandidateSymbol
)
SELECT t1.ID,
t1.CandidateId AS Candidate,
t2.Votes,
CASE WHEN t2.Votes = (SELECT MAX(Votes) FROM Votes_CTE)
THEN 'Winner'
ELSE 'Loser' END AS Status
FROM Candidate t1
LEFT JOIN Votes_CTE t2
ON t1.CandidateId = t2.CandidateSymbol