SQL SERVER 2005的集合操作运算包含了UNION, EXCEPT, INTERSECT。其中,UNION 返回两个输入中的行的合集,EXCEPT 返回位于输入1但不位于输入2的行,INTERSECT 返回在两个输入中都存在的行。
1、UNION 是我们经常用到的,它有两种形式,一种是UNION DISTINCT, 另一种是UNION ALL。它们的不同之处是UNION DISTINCT移除了重复行,但UNION ALL组合了两个输入中所有行的结果集,并包含重复行。
2、EXCEPT 也存在DISTINCT和ALL两种概念,不过目前的SQL版本只支持DISTINCT,对于ALL需要自已动手为实现。
我们看一下面的SQL
-- except distinct
-- 找出位于输入1,但不位于输入2的行。
select Country, Region, City from [Northwind].[dbo].[Employees]
except
select Country, Region, City from [Northwind].[dbo].[Customers];
-- except all
-- 位于输入1的字段出现了n次,位于输入2的字段出现了m次, 找出其中n>m的行。
with except_all as
(
select ROW_NUMBER() over(partition by Country, Region, City
order by Country, Region, City) as rn,
Country, Region, City
from [Northwind].[dbo].[Employees]
except
select ROW_NUMBER() over(partition by Country, Region, City
order by Country, Region, City) as rn,
Country, Region, City
from [Northwind].[dbo].[Customers]
)
select Country, Region, City from except_all
-- 找出位于输入1,但不位于输入2的行。
select Country, Region, City from [Northwind].[dbo].[Employees]
except
select Country, Region, City from [Northwind].[dbo].[Customers];
-- except all
-- 位于输入1的字段出现了n次,位于输入2的字段出现了m次, 找出其中n>m的行。
with except_all as
(
select ROW_NUMBER() over(partition by Country, Region, City
order by Country, Region, City) as rn,
Country, Region, City
from [Northwind].[dbo].[Employees]
except
select ROW_NUMBER() over(partition by Country, Region, City
order by Country, Region, City) as rn,
Country, Region, City
from [Northwind].[dbo].[Customers]
)
select Country, Region, City from except_all
通过except(默认为distinct),我们可以获得输入1中存在但在输入2中不存在的行,是以输入1为基准的。
这里的except all形式使用了一个cte和row_number()来实现了,以Country、Region、City这几个字段进行分区(并排序)来为行分配行号,通过对employees和customers这两个表中的行号及相关字段进行except操作,返回位于输入1但不位于输入2的行。
我们看一下面的例子:
Code
未完........