加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 数据库 > MsSql > 正文

sql – 复杂的Postgres查询

发布时间:2020-05-24 18:30:06 所属栏目:MsSql 来源:互联网
导读:我有一个像下面的数据库模式 – (Country table)| Country | Country Code| ------------------------- ABC A BCD B (组织表) |组织|国家代码|组织代码 Org 1 A O1Org 2 B

我有一个像下面的数据库模式 –

(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

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读