从SQL查询中排除特定记录集

时间:2016-06-07 05:27:03

标签: sql join sql-server-2008-r2

我有一个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');

4 个答案:

答案 0 :(得分:2)

只需检查附加条件

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

不需要子查询

答案 1 :(得分: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;

答案 2 :(得分:1)

如果您还想照顾Order By,请使用此选项。否则只需使用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

答案 3 :(得分: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