2017-04-06 66 views
1

此查询看起来可能很基本,但我处于相当基础的级别。如何加入两个字段,其中一个可能为空

因此,这里是我的数据 - 很抱歉的格式,我已经试过了帮助,但该表格式显然不是为我工作(可有人请指教?)以下

表1

ID |Country 
---| ------- 
1 | UK 
1 | IE 
1 | US 
2 | UK 
2 | FR 

表2

ID |Country 
---| ------- 
1 | UK 
1 | IE 
2 | UK 

我想要的结果是这样的

Table 1----- | ----Table 2 

ID |Country |-----ID |Country 
---| ------- |--------|-------- 
1 | UK  | 1  | UK 
1 | IE  | 1  | IE 
1 | US  | 1  | NULL 
2 | UK  | 2  | UK 
2 | FR  | 2  | NULL 

但更具体的我想识别空的,这样我得到这样的结果

Table 1----- | ----Table 2 

ID |Country |-----ID |Country 
---| ------- |--------|-------- 
1 | US  | 1  | NULL 
2 | FR  | 2  | NULL 

到目前为止,我所使用的代码是:

select * 
from table1 t1 
left outer join table2 t2 on t1.id = t2.id and t1.country = t2.country 
where t1.id is not null 
and t2.country is null 
+0

你可以使用CTRL + K表格格式设置 – paul

+0

是什么t2.upc? – GuidoG

+0

谢谢保罗。 @ GuidoG - 对不起,这是一个错字,我现在更新了它 – bobtastic

回答

0

你接近,你只需要使用isnull()coalesce()

select 
    t1.id 
    , t1.country 
    , t2_Id = isnull(t2.id,t1.id) 
    , t2_country = t2.country 
from table1 t1 
left outer join table2 t2 on t1.id = t2.id and t1.country = t2.country 
where t1.id is not null 
    --and t2.country is null 

rextester 演示http://rextester.com/XCNH52338

回报:

+----+---------+-------+------------+ 
| id | country | t2_Id | t2_country | 
+----+---------+-------+------------+ 
| 1 | UK  |  1 | UK   | 
| 1 | IE  |  1 | IE   | 
| 1 | US  |  1 | NULL  | 
| 2 | UK  |  2 | UK   | 
| 2 | FR  |  2 | NULL  | 
+----+---------+-------+------------+ 

t2.country is null

返回附加滤波器:

+----+---------+-------+------------+ 
| id | country | t2_Id | t2_country | 
+----+---------+-------+------------+ 
| 1 | US  |  1 | NULL  | 
| 2 | FR  |  2 | NULL  | 
+----+---------+-------+------------+ 

两者之间的主要区别是coalesce()可以支持2个以上的参数,并且它选择第一个不是null。两者之间更多的区别是answered here.

coalesce()是标准的ANSI sql,所以它在大多数RDBMS中都可用。 isnull()是特定于SQL Server的。

参考:

1

试试这个

select t1.id, t1.country, isnull(t2.id, t1.id) AS T2_ID, t2.country 
from table1 t1 
left outer join table2 t2 on t1.id = t2.upc and t1.country = t2.country 

如果你想只显示你在t2中有空值的那些,你可以添加

where t2.id is null 

但是,如果你想显示所有记录,只要把它没有WHERE条件

+0

嗨Agapwlesu,我试着把你的代码翻译成我的表格,但我不断收到一个错误,指出“ isnull函数需要2个参数。“你能帮忙吗?选择\t st.upc, \t \t st.RELEASE_STATUS, \t \t st.OWNING_COUNTRY, \t \t st.GRS_GRANDFATHER, \t \t st.GRCS_DATA_RECEIVED, \t \t st.LEGAL_RIGHT_COUNTRY, \t \t \t IIF(ISNULL(RS .id),st.id,rs.id)AS T2_ID,iif(isnull(rs.id),“NULL”,rs.country)AS T2_Country from dbo。[UATinGRS rows] st left outer join dbo.UATBatchOneResult rs上的st.upc = rs.upc和st.LEGAL_RIGHT_COUNTRY = rs.LEGAL_RIGHT_COUN TRY – bobtastic

+0

这不是你如何在sql server中使用[**'isnull()'**](https://msdn.microsoft.com/en-us/library/ms184325.aspx)。 – SqlZim

+0

自从我使用sqlserver以来已经有一段时间了,但我希望你有这个想法(需要测试null t2.id并从t1.id或国家这个词替换为“NULL”)并进行翻译。我将编辑修复它。 – AgapwIesu

相关问题