Answers:
您可以CTE
在一个查询中包含多个,并重用a CTE
:
WITH cte1 AS
(
SELECT 1 AS id
),
cte2 AS
(
SELECT 2 AS id
)
SELECT *
FROM cte1
UNION ALL
SELECT *
FROM cte2
UNION ALL
SELECT *
FROM cte1
但是请注意,这SQL Server
可能会重新评估CTE
其访问的每个时间,因此,如果您使用的是类似的值RAND()
,NEWID()
等等,它们可以在之间进行切换CTE
通话。
[ ,...n ]
in [ WITH <common_table_expression> [ ,...n ] ]
。示例C,“在单个查询中使用多个CTE定义”,显式地指出了这一点。可悲的是,SQL 2008和2000的文档中未提供此示例。 (例如,OP在发布问题时未提供示例)
UNION ALL
您当然可以在单个查询表达式中具有多个CTE。您只需要用逗号分隔即可。这是一个例子。在下面的示例中,有两个CTE。一个被命名CategoryAndNumberOfProducts
,第二个被命名ProductsOverTenDollars
。
WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
SELECT
CategoryID,
CategoryName,
(SELECT COUNT(1) FROM Products p
WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
FROM Categories c
),
ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
SELECT
ProductID,
CategoryID,
ProductName,
UnitPrice
FROM Products p
WHERE UnitPrice > 10.0
)
SELECT c.CategoryName, c.NumberOfProducts,
p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
INNER JOIN CategoryAndNumberOfProducts c ON
p.CategoryID = c.CategoryID
ORDER BY ProductName