我有一张选票,每位选民获得3票,从10名不同候选人中选出。投票1分配3分,投票2分2分,投票3分1分。
我有以下SQL查询总计从每个投票中获得的积分数(因此投票1,2和3的单独结果)。
我需要做的是将所有这些结果放在一个表中,但我不太清楚从哪里开始。
SELECT cn.cand_name, (count(vote_1) * 3) as vote_1 FROM candidate_votes cv Inner Join candidate_names cn ON cv.vote_1 = cn.cand_number GROUP BY cand_name;
SELECT cn.cand_name, (count(vote_2) * 2) as vote_2 FROM candidate_votes cv Inner Join candidate_names cn ON cv.vote_2 = cn.cand_number GROUP BY cand_name;
SELECT cn.cand_name, (count(vote_3) * 1) as vote_3 FROM candidate_votes cv Inner Join candidate_names cn ON cv.vote_3 = cn.cand_number GROUP BY cand_name;
我有以下结果表:
Voter_number Vote_1 Vote2 Vote3
123 cand_1 cand_3 cand_2
456 cand_2 cand_1 cand_3
789 cand_2 cand_3 cand_1
以下候选名称表:
cand_number cand_name
cand_1 Dave
cand_2 Sarah
cand_3 Nigel
所以我正在寻找的结果看起来像是:
Candidate Votes
Dave 6
Sarah 7
Nigel 5
答案 0 :(得分:4)
SELECT
cn.cand_name,
count(cv1.vote_1) * 3 as vote_1,
count(cv2.vote_2) * 2 as vote_2,
count(cv3.vote_3) as vote_3
FROM
candidate_names cn
LEFT JOIN
candidate_votes cv1 ON cv1.vote_1 = cn.cand_number
LEFT JOIN
candidate_votes cv2 ON cv2.vote_2 = cn.cand_number
LEFT JOIN
candidate_votes cv3 ON cv3.vote_3 = cn.cand_number
GROUP BY cn.cand_name;
这也允许您添加所有选票
(count(cv1.vote_1) * 3) +
(count(cv2.vote_2) * 2) +
count(cv3.vote_3) as totalvotes
编辑:行正在乘以JOIN,这就是为什么它对于cand2和cand3来说是错误的
SELECT
cn.cand_name,
SUM(CASE WHEN cv.vote_1 = cn.cand_number THEN 3 ELSE 0 END) as vote_1,
SUM(CASE WHEN cv.vote_2 = cn.cand_number THEN 2 ELSE 0 END) as vote_2,
SUM(CASE WHEN cv.vote_3 = cn.cand_number THEN 1 ELSE 0 END) as vote_3
FROM
candidate_names cn
JOIN
candidate_votes cv ON cn.cand_number IN (cv.vote_1, cv.vote_2, cv.vote_3)
GROUP BY cn.cand_name;
答案 1 :(得分:3)
SELECT cn.cand_name
, COALESCE(cv1.cnt_1,0)
, COALESCE(cv2.cnt_2,0)
, COALESCE(cv3.cnt_3,0)
, 3*COALESCE(cv1.cnt_1,0) + 2*COALESCE(cv2.cnt_2,0)
+ 1*COALESCE(cv3.cnt_3,0) AS total
FROM candidate_names AS cn
LEFT JOIN
( SELECT vote_1 AS vote
, COUNT(*) AS cnt_1
FROM candidate_votes cv
GROUP BY vote_1
) AS cv1
ON cv1.vote = cn.cand_number
LEFT JOIN
( SELECT vote_2 AS vote
, COUNT(*) AS cnt_2
FROM candidate_votes cv
GROUP BY vote_2
) AS cv2
ON cv2.vote = cn.cand_number
LEFT JOIN
( SELECT vote_3 AS vote
, COUNT(*) AS cnt_2
FROM candidate_votes cv
GROUP BY vote_3
) AS cv3
ON cv3.vote = cn.cand_number
答案 2 :(得分:2)
SELECT
Candidate = n.cand_name,
Votes = SUM(s.vote_weight)
FROM (
SELECT
cand_number = CASE x.weight
WHEN 1 THEN Vote3
WHEN 2 THEN Vote2
WHEN 3 THEN Vote1
END,
vote_weight = x.weight
FROM candidate_votes v
CROSS JOIN (SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3) x (weight)
) s
INNER JOIN candidate_names n ON s.cand_number = n.cand_number
GROUP BY n.cand_name