Complex Postgres query

后端 未结 1 1167
无人及你
无人及你 2020-12-22 00:54

I have a db schema like following -

(Country table)
| Country | Country Code| 
-------------------------
    ABC         A 
    BCD         B
相关标签:
1条回答
  • 2020-12-22 01:27

    All you need to do is to run an aggregate query:

    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 
    

    Now, you ask: where is the Corridor column? The answer is: use the string_agg function:

    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 
    
    0 讨论(0)
提交回复
热议问题