如何在SQL Server 2008中联合多个WITH子句?

时间:2015-10-02 00:49:53

标签: sql-server

例如,我有2个或更多WITH个子句,类似下面附带的代码作为例子。

如何将多个WITH子句一起合并?请多多建议。

SQL Server:

-- WITH clause 1
WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
AS
(
    SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
    FROM Sales.SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
)
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM Sales_CTE
GROUP BY SalesYear, SalesPersonID

-- WITH clause 2
WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
AS
(
    SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
    FROM Sales.SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
)
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM Sales_CTE
GROUP BY SalesYear, SalesPersonID

-- WITH clause 3
WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
AS
(
    SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
    FROM Sales.SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
)
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM Sales_CTE
GROUP BY SalesYear, SalesPersonID

1 个答案:

答案 0 :(得分:1)

仅用,分隔,然后移除WITH

WITH
  sum_sales1 AS 
  (
      --Code here
  ) 
  ,sum_sales2 AS 
  (
       --Code here 
  )

 SELECT * FROM sum_sales1
 UNION
 SELECT * FROM sum_sales2