在列中检查Null / Not Null

时间:2016-06-01 18:07:23

标签: sql sql-server

编写以下查询的有效方法

where col_1 is not null and((col_2 is not null and col_3 is not null)<br/>
                                           or (col_4 is not null and Col_5 is not null)<br/>
                                           or(col_3 is not null and col_4 is not null)<br/>
                                           or(col_2 is not null and Col_5 is not null)<br/>
                                           )<br/>

<br/>
<br/>
<br/>
col_1 is null and ((col_2 is null and col_3 is null and col_4 is null and col_5 is null)<br/>
    or (col_2 is not null and col_3 is null and col_4 is null and col_5 is null)<br/>
    or (col_2 is  null and col_3 is not null and col_4 is null and col_5 is null)<br/>
    or (col_2 is  null and col_3 is null and col_4 is not null and col_5 is null)<br/>
    or (col_2 is  null and col_3 is null and col_4 is null and col_5 is not null)<br/>
    )<br/>

2 个答案:

答案 0 :(得分:0)

只需将条件映射到0和1,这样就可以累加匹配数量:

case when col1 is not null then 1 else 0 end +
case when col2 is not null then 1 else 0 end +
case when col3 is not null then 1 else 0 end +
case when col4 is not null then 1 else 0 end +
case when col5 is not null then 1 else 0 end = 2

...类似地

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 +
case when col4 is null then 1 else 0 end +
case when col5 is null then 1 else 0 end >= 3

答案 1 :(得分:0)

这是关于离散数学中逻辑的问题。 对于第一部分,您只需要

Where col1 is not null 
AND (
       (col3 is not null OR col5 is not null)
       AND
       (col4 is not null OR col2 is not null)
    )