如何相互减去查询结果?

时间:2014-05-01 16:38:33

标签: sql sql-server-2008

请考虑以下

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_2中减去#list_3#list_1中的值,以便我得到差异?

我在SQL Server 2008上。如果我看到这一切都错了,请告诉我。非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

您可以使用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 :(得分:2)

类似

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

不需要临时表来执行此操作。

相关问题