Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

mysql

I have a table like this:

Votes (id, person, positive_vote, negative_vote)

I want to group by person and and sort by total votes for each person. I know how to get the total sum of a single column for a group, but I can't figure out how to get the total of all the sum for each group (the total votes).

Here's what I have so far:

SELECT person, sum(positive_vote), sum(negative_vote) FROM Votes GROUP BY person;
like image 432
Scott Bartell Avatar asked Sep 28 '12 02:09

Scott Bartell


1 Answers

Try,

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
like image 140
John Woo Avatar answered Oct 21 '22 04:10

John Woo