sql - Complex Postgres query -
i have db schema following -
(country table) | country | country code| ------------------------- abc bcd b
(organization table)
|organization | country code | organization code
org 1 o1 org 2 b o2 org 3 o3
(transaction table)
| organization | export(in $) | import(in $)|
o1 x1 y1 o2 x2 y2 o3 x3 y3
i want result set -
| corridor | total export | total import | ------------------------------------------ abc-bcd x1+x2+x3 y1+y2+y3
corridor column should combination of countries in country table.
how can form query implement logic? thanks
all need run aggregate query:
select sum(t.export) totalexport, sum(t.import) totalimport country c inner join organization o on c.country_code = o.country_code inner join transaction t on o.organization_code = t.organization_code
now, ask: corridor column? answer is: use string_agg function:
select string_agg(distinct c.country, '-' order c.country) corridor, sum(t.export) totalexport, sum(t.import) totalimport country c inner join organization o on c.country_code = o.country_code inner join transaction t on o.organization_code = t.organization_code
Comments
Post a Comment