我有一个像下面的数据库模式 –
(Country table) | Country | Country Code| ------------------------- ABC A BCD B
(组织表)
Org 1 A O1 Org 2 B O2 Org 3 A O3
(交易表)
|组织|出口(以美元计)|导入(以$计)|
O1 X1 Y1 O2 X2 Y2 O3 X3 Y3
我希望结果集如下 –
| Corridor | Total Export | Total Import | ------------------------------------------ ABC-BCD X1+X2+X3 Y1+Y2+Y3
Corridor列应该是Country表中所有国家/地区的组合.
如何形成查询来实现此逻辑?谢谢
解决方法
您需要做的就是运行聚合查询:
select sum(t.export) as TotalExport,sum(t.import) as TotalImport FROM country c inner join Organization o on c.Country_Code = o.Country_Code inner join Transaction t on o.organization_code = t.organization_code
现在,您问:Corridor专栏在哪里?答案是:使用string_agg功能:
select string_agg(DISTINCT c.country,'-' ORDER BY c.country) as Corridor,sum(t.export) as TotalExport,sum(t.import) as TotalImport FROM country c inner join Organization o on c.Country_Code = o.Country_Code inner join Transaction t on o.organization_code = t.organization_code