Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 复杂Postgres查询_Sql_Postgresql - Fatal编程技术网

Sql 复杂Postgres查询

Sql 复杂Postgres查询,sql,postgresql,Sql,Postgresql,我有一个db模式,如下所示- (Country table) | Country | Country Code| ------------------------- ABC A BCD B (组织机构表) |组织机构|国家代码|组织机构代码 (交易表) |组织|出口(美元)|进口(美元)| 我希望结果集是这样的- | Corridor | Total Export | Total Import | ----------------------

我有一个db模式,如下所示-

(Country table)
| Country | Country Code| 
-------------------------
    ABC         A 
    BCD         B
(组织机构表)

|组织机构|国家代码|组织机构代码 (交易表)

|组织|出口(美元)|进口(美元)| 我希望结果集是这样的-

| Corridor | Total Export | Total Import |
------------------------------------------
  ABC-BCD      X1+X2+X3       Y1+Y2+Y3

“道路”列应为国家/地区表中所有国家/地区的组合


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

您只需运行聚合查询:

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 
现在,您会问:走廊柱在哪里?答案是:使用以下功能:

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查询”不是很具体。我不认为您的查询可能特别复杂,但您最好强调一下它给您带来的最大麻烦。是多表联接吗?合计总数?定义问题?
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 
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