簡體   English   中英

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

[英]Sum the values of multiple rows with the same column value in 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,但它只顯示了應該出現的行的一小部分。 我怎么能得到上表中的結果?

使用此作為您的查詢:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM