您的位置:首页 > 数据库

SQL SERVER 2005 集合操作(except distinct, except all, intersect distinct, intersect all)

2008-08-29 16:45 148 查看
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
通过except(默认为distinct),我们可以获得输入1中存在但在输入2中不存在的行,是以输入1为基准的。

这里的except all形式使用了一个cte和row_number()来实现了,以Country、Region、City这几个字段进行分区(并排序)来为行分配行号,通过对employees和customers这两个表中的行号及相关字段进行except操作,返回位于输入1但不位于输入2的行。

我们看一下面的例子:

select ROW_NUMBER() over(partition by Country, Region, City order by Country, Region, City) as rn,Country, Region, City

from [Northwind].[dbo].[Employees]

select ROW_NUMBER() over(partition by Country, Region, City order by Country, Region, City) as rn, Country, Region, City

from [Northwind].[dbo].[Customers]

组合USA WA Seattle
返回输入1:

rn Country Region City

1 USA WA Seattle

2 USA WA Seattle

返回输入2:

rn Country Region City

1 USA WA Seattle

可见组合USA WA Seattle将会是返回的行。

组合USA WA Tacoma
输入1:

rn Country Region City

1 USA WA Tacoma

输入2:无返回记录

所以USA WA Tacoma组合也是合符规格的返回行。

组合USA WA Kirkland
输入1:

rn Country Region City

1 USA WA Kirkland

输入2:

rn Country Region City

1 USA WA Kirkland

它们的rn是相同的,不会在返回行中出现。

未完........
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: