我有两个表,如下所示:
表A
-------
AGENCY_ID | ISSUE_YEAR | AMOUNT_ISSUED
00101 | 1996 | 3000
00123 | 1996 | 4000
00165 | 1996 | 3450
00231 | 1996 | 6000
表B
-------
AGENCY_ID | ISSUE_YEAR | AMOUNT_EXPIRED
00101 | 1996 | 4000
00101 | 1997 | 2550
00123 | 1996 | 1250
00123 | 1997 | 1300
00165 | 1996 | 3333
00165 | 1997 | 3124
00231 | 1996 | 1232
00231 | 1997 | 2422
应将哪些连接在一起,合并共享列,并将缺失值填充为0,如下所示:
TABLE JOINED_A_B
-------
AGENCY_ID | ISSUE_YEAR | AMOUNT_EXPIRED | AMOUNT_ISSUED
00101 | 1996 | 4000 | 3000
00101 | 1997 | 2550 | 0
00123 | 1996 | 1250 | 4000
00123 | 1997 | 1300 | 0
00165 | 1996 | 3333 | 3450
00165 | 1997 | 3124 | 0
00231 | 1996 | 1232 | 6000
00231 | 1997 | 2422 | 0
我尝试使用UNION
来加入它们,但结果表的尺寸始终与UNION
运算符(SELECT A UNION SELECT B
左侧)中的尺寸相同。在没有列AMOUNT_EXPIRED
的表中。)
如何正确执行此操作?也许联盟不是一个好选择?
谢谢!
答案 0 :(得分:2)
您似乎想要left join
和coalesce()
:
select b.*, coalesce(a.amount_issued, 0) as amount_issued
from b left join
a
on b.agency_id = a.agency_id and b.issue_year = a.issue_year;