如何对postgresql中的两列求和?

时间:2019-04-21 05:25:48

标签: sql 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

我该怎么做?

2 个答案:

答案 0 :(得分:2)

一种数据透视查询应执行此任务:

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) |

答案 1 :(得分:1)

为了提高效率,最好透视数据而不是在in中使用orjoin。所以,我建议:

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;