在MySQL中使用相同的列值对多行的值求和

时间:2017-03-01 14:49:45

标签: php mysql

我有以下结构:

+====================================================================+
+     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              +
+====================================================================+

此表显示每个城市每个政党的投票数。我需要一个查询,它总结了每一方的所有投票数和百分比。所以上表应该是这样的:

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

因此,它应该省略城市并总结每一方的投票数和百分比。我目前的查询:

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

我尝试了GROUP BY PartyName,但它只显示了应该出现的一小部分行。我怎样才能在上表中得到结果?

1 个答案:

答案 0 :(得分:9)

将此作为您的查询:

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