[英]postgres: sum if count distinct id = 1
如何對具有不同 ID 的總計求和並避免將總計加起來兩次?
桌子:
id | total | quantity |
-----------------------
1 | 50 | 1 |
1 | 50 | 2 |
預期結果:
sum of total | sum of quantity |
---------------------------------
50 | 3 |
一種方法是:
select id, sum(distinct total), sum(quantity)
from t
group by id;
也就是說,當您需要sum(distinct)
時,您的數據有問題。 我從未在“真實”代碼中使用過它; 僅用於這樣的演示。 通常這意味着數據是查詢的結果,聚合應該有點不同。 或者數據中缺少另一個id
(與添加的值分開)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.