需要合理的帮助来实现以下方案

时间:2016-06-01 11:25:52

标签: sql-server sql-server-2008-r2

需要在下面的代码中返回带有注释行的行"应该作为问题返回"。

这可以使用第四列快速完成,但想象一下我没有第四列。

如何返回标记为'的列应作为问题返回'

';with temp as (
select 'A' col1,'B' col2,'C' col3, 'Problem' col4--Should return as a problem
union ALL
select null, null, null,'Problem' --Should return as a problem
union ALL
select null, 'B', 'C','Problem' --Should return as a problem
union ALL
select 'A','B',null,'Problem' --Should return as a problem
union ALL
select 'A',null,'C','Problem' --Should return as a problem
union ALL
select 'A',null,null,'Not a Problem' --Should NOT return as a problem
union ALL
select null, 'B', null,'Not a Problem' --Should NOT return as a problem
union ALL
select null,null,'C','Not a Problem' --Should NOT return as a problem
)
select * from temp WHERE  COALESCE( col1, col2, col3) IS NOT NULL 
                     or COALESCE( col1, col2, col3) IS NULL'

2 个答案:

答案 0 :(得分:2)

您似乎想要返回至少有两个NULL值的行。这是一种方式:

where ((case when col1 is null then 1 else 0 end) +
       (case when col2 is null then 1 else 0 end) +
       (case when col3 is null then 1 else 0 end)
      ) = 2

答案 1 :(得分:0)

select *from temp where
(col1 is not null and (col2 is  null and col3 is  null)) or
(col2 is not null and (col1 is  null and col3 is  null)) or
(col3 is not null and (col1 is  null and col2 is  null))