2016-06-07 75 views
1

我有一個SQL查詢,並希望取回這組數據集:排除特定的記錄從SQL查詢

SELECT 
    Reference, DeliveryDate, SecondaryDate, PurchaseId, 
    ItemDescription, Status 
FROM 
    PLAYBOOK 
WHERE 
    (Supplier='PLAY') AND (Status = '0') 
ORDER BY 
    DeliveryDate DESC; 

但是我希望排除第一個查詢下方檢索到的數據集:

SELECT 
    Reference, DeliveryDate, SecondaryDate, PurchaseId, 
    ItemDescription, Status 
FROM 
    PLAYBOOK 
WHERE 
    (Supplier = 'PLAY') AND (Status = '0') AND (Tax = 'Yes') 
    AND (Problem = 'damaged'); 
+0

是'Reference'唯一的關鍵? – morcen

回答

1

利用這一點,如果你要照顧令的通過也。否則只用except

select * from 
(
SELECT Reference, DeliveryDate, SecondaryDate, PurchaseId, 
ItemDescription, Status FROM PLAYBOOK 
WHERE (Supplier='PLAY') AND (Status = '0') 

EXCEPT 

SELECT Reference, DeliveryDate, SecondaryDate, PurchaseId, 
ItemDescription, Status FROM PLAYBOOK 
WHERE (Supplier='PLAY') AND (Status = '0') AND (Tax = 'Yes') AND (Problem = 'damaged') 
) t1 
ORDER BY DeliveryDate DESC 
+1

我爲其他人投票而跳投,他們看起來很優雅,但沒有奏效。這樣做。 –

0

要回答您的具體問題(無需評論您所要求的是否是一個好主意):

SELECT Reference, DeliveryDate, SecondaryDate, PurchaseId, 
ItemDescription, Status, FROM PLAYBOOK 
WHERE (Supplier='PLAY') AND (Status = '0') 
AND Reference NOT IN (
    SELECT Reference FROM PLAYBOOK 
    WHERE (Supplier='PLAY') 
    AND (Status = '0') 
    AND (Tax = 'Yes') 
    AND (Problem = 'damaged') 
) 
ORDER BY DeliveryDate DESC 
2

Just檢查附加條件

SELECT Reference, DeliveryDate, SecondaryDate, PurchaseId, 
ItemDescription, Status, FROM PLAYBOOK 
WHERE (Supplier='PLAY') AND (Status = '0') 
AND (Tax != 'Yes') AND (Problem != 'damaged') 
ORDER BY DeliveryDate DESC 

無需子查詢

+0

您的查詢無法檢索Tax ='Yes'和Problem <>'damaged'的記錄。 –

+0

@WangWei不是一個或它是一個AND – Sherlock

+0

託比只想排除(供應商='播放')和(狀態='0')AND(稅收='是')和(問題='受損'),但您的查詢也排除了Tax ='Yes'並且Problem是別的東西,而不是'損壞'的情況 –

1

你就不能使用一個查詢:

SELECT Reference, DeliveryDate, SecondaryDate, PurchaseId,ItemDescription, Status 
FROM PLAYBOOK 
WHERE (Supplier='PLAY') AND (Status = '0') AND ((Tax <> 'Yes') AND (Problem <> 'damaged')) 
ORDER BY DeliveryDate DESC; 
+0

雖然和我的答案一樣:3,並且提前回答了我的問題 – Sherlock