将两个SQL查询的结果合并到一个表中,但不使用联合

时间:2019-05-15 15:14:35

标签: sql postgresql

下面有两个表,我想生成第三个表,其中按名称分组了进口值和出口值的总和。

表名:公司

country | name
canada     a
usa        b 
china      c
france     d

表格名称:订单

id| importer | exporter | value
23    canada      usa        10  
24     usa        china      50
25    canada      china      10
26    france       usa       40

例如,我可以使用联接分别生成导入和导出表的总和:

进口商总数

select name, sum(value)
from orders
full outer join companies
on orders.importer = companies.country

我希望看到一个表格,该表格将进口总额和出口总额按名称分组。进口和出口总和是订单表中值列上的总和。我对于是否必须在这里使用子查询感到困惑。

示例表

Name |  sum of importer  | sum of exporter
a        20                   0
b        50                   50
c         0                   60
d        40                   0

4 个答案:

答案 0 :(得分:1)

'''其实很简单..用下面的-

select c.name, IFNULL(sum(i.value),0) as sum_of_imports, IFNULL(sum(e.value),0) as sum_of_exports from companies c
Left join orders i on c.country = i.importer
Left join orders e on c.country = e.exporter
group by c.name
order by c.name asc;

答案 1 :(得分:0)

为此,您需要分别使用两个full outer join,并根据name列将它们加入。

有效查询是:

select g1.name, g1.sumofimporter, g2.sumofexporter
from (
     select c.name
            ,COALESCE(sum(o1.value), 0) as sumofimporter 
     from companies c
     full outer join orders o1 on o1.importer = c.country
     group by c.name
) g1
join (
    select c.name
           ,COALESCE(sum(o2.value), 0) as sumofexporter
    from companies c
    full outer join orders o2 on o2.exporter = c.country
    group by c.name
) g2 on g2.name = g1.name
order by g1.name

注意:由于该帖子是关于postgresql的,所以我在SQL Server上创建了一个有效的演示用于测试。 请找到demo on db<>fiddle

答案 2 :(得分:0)

检查此-

    SELECT A.name,A.sum_of_importer,COALESCE(SUM(O2.value),0)  sum_of_exporter
FROM
(
    SELECT C.name,C.country,COALESCE(SUM(Value),0) AS sum_of_importer 
    FROM Companies C
    LEFT JOIN orders O     ON C.country = O.importer
    GROUP BY  C.name,C.country
)A
LEFT JOIN orders O2 ON  A.country = O2.exporter
GROUP BY A.name,A.sum_of_importer
ORDER BY 1

答案 3 :(得分:0)

我会这样解决:

WITH importer AS (SELECT orders.importer, SUM(orders.value) AS t_import
                  FROM orders
                  GROUP BY 1),
     exporter AS (SELECT orders.exporter, SUM(orders.value) AS t_export
                  FROM orders
                  GROUP BY 1)

SELECT c.name, COALESCE(i.t_import, 0) sum_of_import, COALESCE(e.t_export, 0) sum_of_export
FROM company c
         LEFT JOIN importer i ON c.country = i.importer
         LEFT JOIN exporter e ON c.country = e.exporter

这给了我:

name | sum_of_import | sum_of_export
a        20               0
b        50               50
c        0                60
d        40               0

规划时间:0.157 ms

执行时间:0.120 毫秒

我的想法: 我决定将其拆分为两个不同的 CTE,因为这样更容易加入。您可以获得每个国家作为进口商或出口商的价值。然后使用左连接(以免丢失任何未显示为进口商或出口商的国家/地区)。