2014-11-03 39 views
0

提前道歉我覺得我錯過了一些非常愚蠢的事情。 (並且讓我們忽略數據庫結構,因爲我是被鎖定的)。在ColA中搜索對ColB中特定的獨特值進行重複排除ColA中的所有ColA

我有,讓我們使用客戶訂單 - 訂單號可以運送到多個地方。爲了方便起見,我只是出3條,但它可能是比這更(在家中,辦公室,禮品,gift2,禮品3等)

所以我的表是:

客戶訂單:

OrderID MailingID 
-------------------- 
1   1 
1   2 
1   3 
2   1 
3   1 
3   3 
4   1 
4   2 
4   3 

我需要找到的是已發貨到MailingID 1但不是2(基本上我需要找到的是orderID 2和3以上)的OrderID。

如果它的事項,我使用的SQL Express 2012

感謝

回答

0

也許這可以幫助:

create table #temp(
    orderID int, 
    mailingID int 
) 

insert into #temp 
select 1, 1 union all 
select 1, 2 union all 
select 1, 3 union all 
select 2, 1 union all 
select 3, 1 union all 
select 3, 3 union all 
select 4, 1 union all 
select 4, 2 union all 
select 4, 3 

-- find orderIDs that have been shipeed to mailingID = 1 
select 
    distinct orderID 
from #temp 
where mailingID = 1 
except 
-- find orderIDs that have been shipeed to mailingID = 2 
select 
    orderID 
from #temp 
where mailingID = 2 

drop table #temp 
0

簡單Subquery隨着NOT IN運營商應該工作。

SELECT DISTINCT OrderID 
FROM <tablename> a 
WHERE orderid NOT IN (SELECT orderid 
         FROM <tablename> b 
         WHERE b.mailingID = 2) 
相關問題