SQL - 查找缺失数据/​​否定搜索

时间:2009-12-04 17:02:39

标签: sql primary-key

继我的另一篇文章之后...我有一个使用两个字段制作主键的表...

TravelEventID  RemarkNo    Keyword       Text  
 0001            1           TVL          LOWCOST BOOKING  
 0001            2           TVL          CREDIT CARD USED  
 0001            3           PSG          COST CENTRE REQUIRED  
 0001            4           PSG          EMPLOYEE NUM REQUIRED
 0002            1           TVL          CREDIT CARD USED
 0002            2           AGT          BOOKED BY AGENT
 0002            3           AGT          CONFIRM WITH AIRLINE
 0002            4           TVL          LOWEST FARE CONFIRMED
 0002            5           TVL          NO CANCELLATION CHARGE
 0003            1           TVL          LOWCOST BOOKING
 0003            2           TVL          CARRIER : EASYJET
 0003            3           TVL          LOWEST FARE CONFIRMED
 0004            1           TVL          LOWCOST BOOKING
 0004            2           TVL          CREDIT CARD USED

我需要提取Text不包含LOWCOST BOOKING的TravelEventID。从示例表中我只想要0002.

我尝试执行查询,其中Text<>然而,'LOWCOST BOOKING'显然与大多数行匹配,因此我返回所有TravelEventID。

希望我已经解释得很好! 干杯 达伦

2 个答案:

答案 0 :(得分:3)

SELECT DISTINCT T.TravelEventID
  FROM Table T 
 WHERE NOT EXISTS(SELECT * FROM Table T2 WHERE T.TravelEventID = T2.TravelEventID AND T2.Text = 'LOWCOST BOOKING')

答案 1 :(得分:2)

您可以尝试这样的事情

SELECT DISTINCT TravelEventID
FROM Table WHERE TravelEventID NOT IN (
SELECT TravelEventID
FROM Table
WHERE Text = 'LOWCOST BOOKING'
)