7

我有一张这样的桌子:

Votes (id, person, positive_vote, negative_vote)

我想按人分组,并按每个人的总票数排序。我知道如何获得一个组的单个列的总和,但我不知道如何获得每个组的所有总和(总票数)。

这是我到目前为止所拥有的:

SELECT person, sum(positive_vote), sum(negative_vote) FROM Votes GROUP BY person;
4

5 回答 5

18

尝试,

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
于 2012-09-28T02:07:51.077 回答
3

如果您想要每个人的总数,只需减去总和(如果您只想要总票数,则将它们相加

SELECT person, sum(positive_vote), sum(negative_vote),
    SUM(positive_vote)-SUM(negative_vote)
FROM Votes 
GROUP BY person

请注意,我在这里减去了总和,而不是对列本身的差异求和,因为我不知道您如何在表中存储数据,并且 NULL 可以用数学做一些有趣的事情。

于 2012-09-28T02:07:45.563 回答
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;
于 2012-09-28T02:07:23.230 回答
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;
于 2012-09-28T02:08:44.903 回答
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
于 2016-02-23T06:19:42.027 回答