忽略连接SQL Server中的空值

时间:2017-07-18 19:14:10

标签: sql-server join

我需要根据表1中的输入从表2中获取详细信息。 表1中可以有空值,但在连接到Table2时,比较中需要忽略空输入

例如 - 如果表1中的纸张为空,则输出应包括属于该主题的所有纸张。 你能建议我可以忽略连接中的空值吗?查询需要在SQL Server中

ID  Paper   Subject Department
------------------------------
1   paper1  Math    Dept1
2   null    Math    Dept1
3   null    null    Dept2
4   paper4  Science Dept2

表2

Paper   Subject Department  details1    details2    details3
paper1  Math    Dept1        D1          D2          D3
paper2  Math    Dept1        D1          D2          D3
Paper1  Science Dept2        D1          D2          D3
Paper2  Science Dept2        D1          D2          D3
Paper3  Science Dept1        D1          D2          D3
Paper4  Science Dept2        D1          D2          D3

输出

 Paper  Subject Department  Details1    Details2    Details3
 paper1 Math    Dept1       D1          D2          D3
 paper2 Math    Dept1       D1          D2          D3
 Paper1 Science Dept2       D1          D2          D3
 Paper2 Science Dept2       D1          D2          D3
 paper4 Science Dept2       D1          D2          D3

2 个答案:

答案 0 :(得分:1)

这是你想要的吗?

SELECT DISTINCT a.* FROM @table2 a
INNER JOIN @table1 b
ON a.[Paper] = b.[Paper] 
OR (b.[Paper] IS NULL AND b.[Subject] = a.[Subject] AND b.[Department] = a.[Department])
OR (b.[Paper] IS NULL AND b.[Subject] IS NULL AND b.[Department] = a.[Department])
ORDER BY a.[Subject]

答案 1 :(得分:1)

  

应提取表2中的所有详细信息   表1中的值,忽略匹配条件中的空值。对于ID 2   在Table1中,由于Paper为null,因此输出应包含所有记录   主题为Math和Dept1,ID为3,因为纸张和主题是   null,所有带Dept2的记录都应该被提取 - madhu 12分钟前

解决方案#1

SELECT ...
FROM dbo.Table1 a INNER JOIN dbo.Table2 b 
ON a.Paper = b.Paper AND a.Subject = b.Subject AND a.Department = b.Department
OR a.Paper IS NULL AND a.Subject = b.Subject AND a.Department = b.Department
OR a.Paper IS NULL AND a.Subject IS NULL AND a.Department = b.Department

解决方案#2

SELECT ...
FROM dbo.Table1 a INNER JOIN dbo.Table2 b 
ON a.Paper = b.Paper AND a.Subject = b.Subject AND a.Department = b.Department
UNION ALL
SELECT ... same columns ...
FROM dbo.Table1 a INNER JOIN dbo.Table2 b 
ON a.Paper IS NULL AND a.Subject = b.Subject AND a.Department = b.Department
UNION ALL
SELECT ... same columns ...
FROM dbo.Table1 a INNER JOIN dbo.Table2 b 
ON a.Paper IS NULL AND a.Subject IS NULL AND a.Department = b.Department