我有两张表,每张表都有三列,都有周数和产品类别,一个有进货金额,另一个有每周所述产品类别的出货金额。我希望加入这两个表,以便获得一个表,其中包含每周每个产品类别的传入和传出金额。
数据看起来像这样:
周数 | 产品类别 | 传入金额 |
---|---|---|
1 | 猫1 | 5 |
4 | 猫2 | 6 |
4 | 猫2 | 2 |
4 | 猫3 | 6 |
11 | 猫1 | 6 |
11 | 猫3 | 4 |
周数 | 产品类别 | 支出金额 |
---|---|---|
2 | 猫1 | 5 |
3 | 猫2 | 6 |
4 | 猫2 | 1 |
4 | 猫2 | 7 |
15 | 猫1 | 6 |
15 | 猫1 | 4 |
当我连接这两个表并对列进行分组以使用以下代码对传入和传出金额求和时,我得到下表作为结果。
SELECT i.week_number
,i.product_category
,o.week_number
,o.product_category
,SUM(i.incoming_amount ) AS sum_incoming_amount
,SUM(o.outgoing_amount ) AS sum_outgoing_amount
FROM incoming AS i
FULL OUTER JOIN outgoing AS o
ON i.week_number = o.week_number AND i.product_category = o.product_category
GROUP BY i.product_category, i.week_number, o.product_category, o.week_number;
周数 | 产品类别 | 周数 | 产品类别 | 传入金额 | 支出金额 |
---|---|---|---|---|---|
1 | 猫1 | 空 | 空 | 5 | 空 |
空 | 空 | 2 | 猫1 | 空 | 5 |
空 | 空 | 3 | 猫2 | 空 | 6 |
4 | 猫2 | 4 | 猫2 | 8 | 8 |
4 | 猫3 | 空 | 空 | 6 | 空 |
11 | 猫1 | 空 | 空 | 6 | 空 |
11 | 猫3 | 空 | 空 | 4 | 空 |
空 | 空 | 15 | 猫1 | 空 | 10 |
在输出中,我试图实现周数和产品类别列的合并,如下所示:
周数 | 产品类别 | 传入金额 | 支出金额 |
---|---|---|---|
1 | 猫1 | 5 | 空 |
2 | 猫1 | 空 | 5 |
3 | 猫2 | 空 | 6 |
4 | 猫2 | 8 | 8 |
4 | 猫3 | 6 | 空 |
11 | 猫1 | 6 | 空 |
11 | 猫3 | 4 | 空 |
15 | 猫1 | 空 | 10 |
我怎样才能实现这个目标?
您需要分别计算传入/传出金额,然后应用
FULL OUTER JOIN
:
COALESCE
函数用于从列列表中选择第一个非 NULL 值。
WITH cte_incoming AS (
SELECT week_number, product_category, SUM(incoming_amount) AS sum_incoming_amount
FROM incoming
GROUP BY week_number, product_category
),
cte_outgoing AS (
SELECT week_number, product_category, SUM(outgoing_amount) AS sum_outgoing_amount
FROM outgoing
GROUP BY week_number, product_category
)
SELECT COALESCE(i.week_number, o.week_number) AS week_number,
COALESCE(i.product_category, o.product_category) AS product_category,
sum_incoming_amount,
sum_outgoing_amount
FROM cte_incoming AS i
FULL OUTER JOIN cte_outgoing AS o
ON i.week_number = o.week_number AND i.product_category = o.product_category
结果:
week_number product_category sum_incoming_amount sum_outgoing_amount
1 cat1 5 null
2 cat1 null 5
3 cat2 null 6
4 cat2 8 8
4 cat3 6 null
11 cat1 6 null
11 cat3 4 null
15 cat1 null 10