2014-05-01 60 views
-1

請考慮我的劇本中,下述如何減去彼此的查詢結果?

select name 
into #list_1 
from table_1 
-- result: a, b, c, d, e 

select name 
into #list_2 
from table_2 
-- result: b, e 

select name 
into #list_3 
from table_3 
-- result: a 

select ?? 
-- result: 1 - 2 - 3 = c, d 

傳播,我有3個臨時表,所有持有人的名字。 #list_1包含完整列表。我如何從#list_1中減去#list_2#list_3中的值,以便我得出差異?

我在SQL服務器2008年。如果我看着這一切都錯了,那麼請讓我知道。任何幫助是極大的讚賞。

回答

1

您可以在SQL Server中使用except。但我更喜歡使用not exists因爲它是標準的SQL:

select l1.name 
from table_1 l1 
where not exists (select 1 from table_2 l2 where l2.name = l1.name) and 
     not exists (select 1 from table_3 l3 where l3.name = l1.name); 
1

select name from Table_1 
except 
select name from Table_2 
except 
Select name From Table_3 

不需要臨時表來做到這一點。