erol_smsr erol_smsr -4 years ago 111
PHP Question

Sum the values of multiple rows with the same column value in MySQL

I have the following structure:

+====================================================================+
+ City | PartyName | VoteCount | VotePercentage +
+--------------------------------------------------------------------+
+ City1 | Party1 | 871 | 1.2 +
+ City2 | Party1 | 580 | 2.3 +
+ City3 | Party1 | 149 | 1.2 +
+ City1 | Party2 | 234 | 0.2 +
+ City2 | Party2 | 533 | 1.3 +
+ City3 | Party2 | 655 | 2.2 +
+====================================================================+


This table shows the votes per political party per city. I need a query that sums all the vote counts and percentages of each party. So the above table should look like:

+=======================================================+
+ PartyName | VoteCount | VotePercentage +
+-------------------------------------------------------+
+ Party1 | 1600 | 4.7 +
+ Party2 | 1422 | 3.7 +
+=======================================================+


So, it should omit the cities and sum the vote counts and percentages of each party. My current query:

SELECT City, PartyName, VoteCount, VotePercentage
FROM elections
ORDER BY PartyName


I've tried GROUP BY PartyName, but then it only shows me a fraction of the rows that should appear. How could I get the result in the table above?

Answer Source

Use this as your query:

SELECT PartyName, SUM(VoteCount), SUM(VotePercentage) FROM elections GROUP BY PartyName
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download