SQL Server:左联接-检查右表列值是否为空

时间:2018-12-04 01:51:15

标签: sql-server tsql join case

我有一个查询,如下所示:

select --this select should always give me 1 record
    tbl1.Id, tbl1.Name, tbl1.Address, tbl2.relNo, 
    CASE WHEN tbl3.Comments IS NOT NULL THEN 1 ELSE 0 END AS 'Required'
from 
    table1 tbl1 
inner join 
    table2 tbl2 on tbl2.Id = tbl1.Id
left join -- This left join table gives me 5 records for one instance
    (select 
         R.Id, C.Comments
     from
         tblC C
     inner join 
         tblR R on R.Id = C.id) tbl3 on tbl3.Id = tbl2.Id

我想在我的左联接给出的行上写一个CASE语句,以检查空值,如上所述,我的最终选择查询总是只返回1行。有没有一种方法可以检查在上述查询中是否检查了我左边联接的所有五个“注释列”值是否为NULL?

2 个答案:

答案 0 :(得分:0)

我想在使用COUNT()分区时使用快捷方式

CASE WHEN COUNT(*) OVER (PARTITION BY tbl3.Id)  =0 THEN 0 ELSE 1 END AS 'Required'

您将必须DISTINCT在上面的输出。另一个选择是GROUP BY并在HAVING子句中进行过滤。

select --this select should always give me 1 record
     tbl1.Id, tbl1.Name, tbl1.Address, tbl2.relNo
From table1 tbl1 
inner join table2 tbl2 on tbl2.Id = tbl1.Id
left join (-- This left join table gives me 5 records for one instance
      SELECT R.Id,
             C.Comments
      FROM tblC C
      INNER JOIN tblR R on R.Id = C.id
 ) tbl3 on tbl3.Id = tbl2.Id     
 GROUP BY 
    Id, Name, Address, relNo
 HAVING 
    COUNT(*) = 5

答案 1 :(得分:0)

这是您要找的吗?

(在从tbl3处选择count(tbl3.id)的情况下,tbl3.Comments为NULL,然后1否则0结束)为'RequiredVal'

select --this select should always give me 1 record
     tbl1.Id, tbl1.Name, tbl1.Address, tbl2.relNo, 
     CASE WHEN tbl3.Comments IS NOT NULL THEN 1 ELSE 0 END AS 'Required'

     , (CASE WHEN (select count(tbl3.id) FROM tbl3 WHERE tbl3.Comments IS NULL) then 1 else 0 end) as 'RequiredVal'

From table1 tbl1 
inner join table2 tbl2 on tbl2.Id = tbl1.Id
left join (-- This left join table gives me 5 records for one instance
      SELECT R.Id,
             C.Comments
      FROM tblC C
      INNER JOIN tblR R on R.Id = C.id
 ) tbl3 on tbl3.Id = tbl2.Id