我有两个 table 并希望在另一个 table 中查询结果

I have two tables and want the result of query in another table

我有 2 个表 Comapnies 和 Trades: 公司:

Country center
Absolute Mathlands
Alice s.p. Wonderland
Arcus t.g. Mathlands
Lil Mermaid Underwater Kingdom

交易:

id seller buyer value
20120125 Alice s.p. Arcus t.g. 100
20120216 Lil Mermaid Absolute 30
20120217 Lil Mermaid Absolute 50
20121107 Lil Mermaid Alice s.p. 10

我使用的查询:

select country
      ,(select sum(value) from trades t1 where c.name = t1.buyer) as imports
      ,(select sum(value) from trades t2 where c.name = t2.seller) as exports
from companies c
group by country
order by country;

我没有得到所需的输出。

要求输出:

country Export Import
Mathlands 30 180
Nothingland 0 0
Underwater Kingdom 90 0
Wonderland 100 40

我得到的是:

country Imports Exports
Mathlands 80 NULL
Nothingland NULL NULL
Underwater Kingdom NULL 90
Wonderland 10 100

您可以使用条件聚合

select c.center 
    , sum(case c.Country when t.seller then value end) export
    , sum(case c.Country when t.buyer then value end) import
from Comapnies c
left join Trades t on c.Country in (t.seller, t.buyer)
group by c.center
order by c.center;

我正在使用您的示例数据中的列名称。

db<>fiddle