时间:2021-07-01 10:21:17 帮助过:7人阅读
UNION DISTINCT会删除重复行。
SELECT country, region, city FROM HR.Employees UNION SELECT country, region, city FROM Sales.Customers;
SELECT country, region, city FROM HR.Employees INTERSECT SELECT country, region, city FROM Sales.Customers;
注意一点,集合运算对行进行比较时,认为两个NULL值相等。
SQL Server不支持内建的INTERSECT ALL运算,需要用替代的解决方案来实现INTERSECT ALL。可以用ROW_NUMBER来实现此需求。
SELECT ROW_NUMBER() OVER(PARTITION BY country, region, city ORDER BY (SELECT 0)) AS rownum, country, region, city FROM HR.Employees INTERSECT SELECT ROW_NUMBER() OVER(PARTITION BY country, region, city ORDER BY (SELECT 0)), country, region, city FROM Sales.Customers;
执行结果:
注意上面的SQL中,在排序函数的OVER子句中使用ORDER BY(SELECT<常量>)是告诉SQL Server不必在意行的顺序。如果想让返回的结果不包含行号,则可以在这个查询基础上定义一个表表达式,如:
WITH INTERSECT_ALL AS ( SELECT ROW_NUMBER() OVER(PARTITION BY country, region, city ORDER BY (SELECT 0)) AS rownum, country, region, city FROM HR.Employees INTERSECT SELECT ROW_NUMBER() OVER(PARTITION BY country, region, city ORDER BY (SELECT 0)), country, region, city FROM Sales.Customers ) SELECT country, region, city FROM INTERSECT_ALL;
SELECT country, region, city FROM HR.Employees EXCEPT SELECT country, region, city FROM Sales.Customers;
注意,在EXCEPT集合运算中,交换两个集合的运算位置会使运算结果不同。
WITH EXCEPT_ALL AS ( SELECT ROW_NUMBER() OVER(PARTITION BY country, region, city ORDER BY (SELECT 0)) AS rownum, country, region, city FROM HR.Employees EXCEPT SELECT ROW_NUMBER() OVER(PARTITION BY country, region, city ORDER BY (SELECT 0)), country, region, city FROM Sales.Customers ) SELECT country, region, city FROM EXCEPT_ALL;
笔记-Microsoft SQL Server 2008技术内幕:T-SQL语言基础-06 集合运算
标签: