[英]Using multiple conditions in where clause of SQL Server
我的数据库中有一个名为finalres
的表,其中包含状态和帐户列表。
我想提取状态不应该在的帐户:
(xxx, ina, nfc)
我还想提取RWD
中状态的帐户,但仅当帐户#为空时。 我写了下面的查询,但它只给出任一条件的结果。 请帮我。
select *
from finalres
where 1 = 0
or (status = 'rwd' and account# is null)
or status not in ('xxx', 'ina', 'nfc')
select * from finalres where
(status='rwd' and account# is null)
or status not in ('xxx','ina','nfc')
您可以在下面的链接中查看此查询:
http://sqlfiddle.com/#!18/11b3d/2
CREATE TABLE finalres
(
[account] int,
[ItemNo] varchar(32),
status varchar(100)
)
INSERT INTO finalres (account, ItemNo, status) VALUES
('1', '453', 'xxx'),
('2', '657', '34'),
(null, '657', 'rwd')
;
account ItemNo status
2 657 34
(null) 657 rwd
您有不想记录的状态列表(xxx、ina、nfc)。 此外,当 account# 为空时,您只需要状态为 RWD 的记录,这意味着您需要将该状态添加到您不想要的状态列表中。 这会给你一个这样的查询:
select
*
from
finalres
where
status not in ('rwd','xxx','ina','nfc')
or (status='rwd' and account is null)
问题是status not in ('xxx','ina','nfc')
允许结果包含任何status
='rwd',即使account#
不为空。 这使得(status='rwd' and account# is null)
变得多余。 您需要在status not in
包含“rwd”。
select
*
from finalres
where 1 = 0
or (status='rwd' and account# is null)
or status not in ('rwd','xxx','ina','nfc')
尝试这个,
select *
from finalres
where (status='rwd' and account# is null)
or status not in ('xxx','ina','nfc')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.