[英]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.