我有一张这样的表:
Votes (id, person, positive_vote, negative_vote)
我想按人分组,并按每个人的总票数排序。我知道如何获得一个组的单个列的总和,但是我无法弄清楚如何获得每个组的总和(总票数)。
这是我到目前为止所拥有的:
SELECT person, sum(positive_vote), sum(negative_vote) FROM Votes GROUP BY person;
答案 0 :(得分:15)
尝试,
SELECT person,
sum(positive_vote) totalPositive,
sum(negative_vote) totalNegative,
(sum(positive_vote) + sum(negative_vote)) totalVotes
FROM Votes
GROUP BY person
-- HAVING (sum(positive_vote) + sum(negative_vote)) < 5
答案 1 :(得分:2)
SELECT Z.person,Z.sum_pv,Z.sum_nv,Z.diff_sum_pv_nv
FROM
(SELECT person, sum(positive_vote) AS sum_pv, sum(negative_vote) sum_nv,sum(positive_vote) - sum(negative_vote) AS diff_sum_pv_nv
FROM Votes GROUP BY person)Z;
答案 2 :(得分:1)
如果您想要每个人的总数,只需减去总和(或者如果您只想要总计数量的选票,则添加它们):
SELECT person, sum(positive_vote), sum(negative_vote),
SUM(positive_vote)-SUM(negative_vote)
FROM Votes
GROUP BY person
注意我在这里减去了总和并且没有总结列本身的差异,因为我不知道你是如何在表中存储数据的,而NULL可以用数学做有趣的事情。
答案 3 :(得分:1)
你的意思是positive_vote和negative_vote的总和吗?
SELECT
person,
SUM(positive_vote) AS positive_votes,
SUM(negative_vote) AS negative_votes,
SUM(positive_vote + negative_vote) AS total_votes
FROM Votes GROUP BY person;
答案 4 :(得分:0)
SELECT person,
sum(positive_vote) as totalPositive,
sum(negative_vote) as totalNegative,
(sum(positive_vote + negative_vote)) as totalVotes
FROM Votes
GROUP BY person