gpt4 book ai didi

sql-server - 合计投票结果

转载 作者:行者123 更新时间:2023-12-02 23:02:50 28 4
gpt4 key购买 nike

我有一张选票,每个选民获得 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

最佳答案

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;

关于sql-server - 合计投票结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6608353/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com