SQL查询:使用空值组合2个表
我对合并两个表有问题。是否可以使用此值组合2个表 表1:SQL查询:使用空值组合2个表,sql,sql-server,Sql,Sql Server,我对合并两个表有问题。是否可以使用此值组合2个表 表1: id no. descrp value 1 A 10 3 C 30 5 E 50 表2: id no. descrp 1 A 2 B 3 C 4 D 5 E 结果: id no. descrp value 1 A
id no. descrp value
1 A 10
3 C 30
5 E 50
表2:
id no. descrp
1 A
2 B
3 C
4 D
5 E
结果:
id no. descrp value
1 A 10
2 B null/0
3 C 30
4 D null/0
5 E 50
我已经尝试联接两个表,但结果无法显示空值。您只需要一个
左外部联接
,它从位于左侧的表中选择所有数据,并在右侧的表位置中找到等效的匹配数据。如果存在匹配项,则返回数据,否则将填充一个NULL
。给你
SELECT t2.[id no], t2.Descrption, t1.amount
FROM table2 t2
Left outer join table1 t1 on t2.[id no]= t1.[id no]
编辑-要将NULL
替换为0,请使用以下查询
SELECT t2.[id no], t2.Descrption, COALESCE(t1.amount,0) FROM table2 t2 Left outer join table1 t1 on t2.[id no]= t1.[id no]
搜索
LEFT JOIN
@aoy24试试这个。。。。从表2中选择t2。[id no],t2.Descrption,COALESCE(t1.amount,0)t2上的表2 t2左外连接表1 t1。[id no]=t1。[id no]@AmneshGoel请在注释中编辑您的答案;)。