复杂的Postgres查询 [英] Complex Postgres query

查看:95
本文介绍了复杂的Postgres查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下数据库模式-

I have a db schema like following -

(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

走廊列应为所有组合

如何构成查询以实现此逻辑?谢谢

How can I form a query to implement this logic? Thanks

推荐答案

所有您需要做的就是运行汇总查询:

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 

您问:走廊列在哪里?答案是:使用 string_agg 函数:

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 

这篇关于复杂的Postgres查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆