繁体   English   中英

MySQL组由多列总和和每个组的总和组成

[英]MySQL group by with multiple column sums and a total sum for each group

我有这样一张桌子:

Votes (id, person, positive_vote, negative_vote)

我想按人分组,并按每个人的总票数排序。 我知道如何获得一个组的单个列的总和,但我无法弄清楚如何获得每个组的总和(总票数)。

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

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

尝试,

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
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;

如果你想总的每个人,只是减去的金额(或增加他们,而不是如果你只是想投票的总数 ):

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

注意我已经减去这里的总和 ,并没有总结列本身的差异,因为我不知道你如何在表中存储数据,而NULL可以用数学做有趣的事情。

你的意思是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;
SELECT person, 
       sum(positive_vote) as totalPositive, 
       sum(negative_vote) as totalNegative,
       (sum(positive_vote + negative_vote)) as totalVotes
FROM Votes 
GROUP BY person

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM