简体   繁体   中英

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?

Use this as your query:

SELECT PartyName, SUM(VoteCount), SUM(VotePercentage) 
FROM elections 
GROUP BY PartyName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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