T-SQL支持3種集合運算:並集(UNION)、交集(INTERSECT)和差集(EXCEPT)。集合運算涉及的兩個查詢不能包含ORDER BY子句。函數
UNION ALL不會對行進行比較,也不會刪除重複行。假設查詢Query1返回m行,查詢Query2返回n行,則Query1 UNION ALL Query2返回(m+n)行。spa
SELECT country, region, city FROM HR.Employees UNION ALL SELECT country, region, city FROM Sales.Customers;
UNION DISTINCT會刪除重複行。code
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值相等。blog
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;
執行結果:ci
注意上面的SQL中,在排序函數的OVER子句中使用ORDER BY(SELECT<常量>)是告訴SQL Server沒必要在乎行的順序。若是想讓返回的結果不包含行號,則能夠在這個查詢基礎上定義一個表表達式,如:it
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集合運算中,交換兩個集合的運算位置會使運算結果不一樣。io
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;