在SQL中需要从包含NULL值的2列中提取值

时间:2012-04-29 02:44:26

标签: sql

我从表中提取记录,条件是

(status_code不在'A')或(status_code不在'C'且SNbr不在'01','02','03)

这两列都可以具有重复值,并且可以包含NULL值。

这是表格数据

status_code              SNbr
A                        01
A                        NULL
A                        04 
NULL                     NULL
NULL                     01
C                        NULL
C                        01
C                        04
B                        01
B                        NULL

所需的O / P

status_code              SNbr
NULL                     NULL
NULL                     01
C                        NULL
C                        04
B                        01
B                        NULL

提前感谢您的帮助

3 个答案:

答案 0 :(得分:1)

select * from <tablename> where 
status_code != 'A' or status_code is null or SNbr is null or
(status_code !='C' and SNbr not in ('01','02','03'))

答案 1 :(得分:0)

[更新]试试这个:

DECLARE @table TABLE (status_code varchar(4), snbr varchar(5))
INSERT INTO @table
SELECT 'A','01'
UNION SELECT 'A',NULL
UNION SELECT 'A','04' 
UNION SELECT NULL,NULL
UNION SELECT NULL,'01'
UNION SELECT 'C',NULL
UNION SELECT 'C','01'
UNION SELECT 'C','04'
UNION SELECT 'B','01'
UNION SELECT 'B',NULL


select * from @table where 
(ISNULL(status_code,'') IN ('C') AND ISNULL(SNbr,'') NOT IN ('01','02','03')) OR
(ISNULL(status_code,'') NOT IN ('C') AND ISNULL(status_code,'') != 'A')

答案 2 :(得分:0)

问题中条件的措辞具有误导性,因为两个单独的条款不能通过OR连接并仍然产生所需的输出。问题中显示的示例输出表明需要强制执行所有规则,而不仅仅是一个或另一个。以下是SQL中WHERE子句的外观:

SELECT * FROM someTable
WHERE COALESCE( status_code, '' ) != 'A' 
AND
( COALESCE ( status_code, '' ) != 'C' 
  OR COALESCE( SNbr, '' ) NOT IN ( '01', '02', '03' )
)
;