我有两个我想合并成一张表。它们有一些常见的列,但我不知道如何正确组合它们。
样品:
表A
Month | Year | Costumer_ID | Total_A |
--------------------------------------
10 | 2014 | 222 | 50 |
1 | 2015 | 111 | 100 |
2 | 2015 | 111 | 200 |
4 | 2015 | 222 | 250 |
表B
Month | Year | Costumer_ID | Total_B |
--------------------------------------
1 | 2015 | 111 | 50 |
2 | 2015 | 333 | 100 |
4 | 2015 | 222 | 250 |
所需结果
Month | Year | Costumer_ID | Total_A | Total_B |
------------------------------------------------
10 | 2014 | 222 | 50 | 0 |
1 | 2015 | 111 | 100 | 50 |
2 | 2015 | 111 | 200 | 0 |
2 | 2015 | 333 | 0 | 100 |
4 | 2015 | 222 | 250 | 250 |
逻辑如下:
在表A中,每年的每个月a的总数不是零,则表中会有记录。因此,并非每年的所有几个月都有每个客户的记录。
表B的工作方式与表A相同,但total_b与total_a不同。因此,在特定的一个月和一年中,客户可能只有一张表格,都可以在其中或中没有记录。
我想生成一个包含每个客户每年每个客户记录的表。如果表A或表B中有相应的记录,则将在结果表中显示每个表的total_a和total_b。如果该表中该表中没有该特定客户端的记录,则总计_a或/and_b在结果表中为零。
这看起来像full outer join
。0
S可以使用coalesce
生成:
SELECT COALESCE(a.month, b.month) AS month,
COALESCE(a.year, b.year) AS year,
COALESCE(a.customerid, b.customerid) AS customerid,
COALESCE(total_a, 0) AS total_a,
COALESCE(total_b, 0) AS total_b
FROM a
FULL OUTER JOIN b ON a.month = b.month AND
a.year = b.year AND
a.customerid = b.customerid
做一个FULL OUTER JOIN
,使用COALESCE
获取0而不是null。
select coalesce(ta.Month, tb.Month) as Month,
coalesce(ta.Year, tb.year) as Year,
coalesce(ta.Costumer_ID, tb.Costumer_ID) as Costumer_ID,
coalesce(ta.Total_A,0) as Total_A,
coalesce(tb.Total_B,0) as Total_B
from tableA ta FULL outer join tableB tb
on ta.year = tb.year
and ta.month = tb.month
and ta.Costumer_ID = tb.Costumer_ID