[英]how to sum two columns in postgresql?
我有以下表格:
公司有:
company country
A us
B UK
C france
交易:
seller buyer amount
A B 10
B C 12
我想得到每個國家的買賣總結。 您可以在同一個國家/地區內進行任何交易
country sum_buyer sum_seller
us 10
UK 10 12
france 12
我怎樣才能做到這一點?
一種透視查詢應該執行此任務:
SELECT c.country,
sum(case when c.company = t.buyer then amount end) as sum_buyer,
sum(case when c.company = t.seller then amount end) as sum_seller
FROM trades t
JOIN companies c ON c.company IN (t.seller, t.buyer)
GROUP BY c.country
ORDER BY 1 DESC
演示: http ://www.sqlfiddle.com/#!15/ 7458d2/15
| country | sum_buyer | sum_seller |
|---------|-----------|------------|
| us | (null) | 10 |
| UK | 10 | 12 |
| france | 12 | (null) |
為了提高效率,它可能是更好的透視數據,而不是使用in
或or
在join
。 所以,我建議:
select c.country,
sum(amount_buyer) as sum_buyer,
sum(amount_seller) as sum_seller
from trades t cross join lateral
(values (t.seller, t.amount, 0),
(t.buyer, 0, t.amount)
) v(company, amount_seller, amount_buyer) join
companies c
on c.company = v.company
group by c.country;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.