你如何与多个 CTE 联合?
Posted
技术标签:
【中文标题】你如何与多个 CTE 联合?【英文标题】:How do you UNION with multiple CTEs? 【发布时间】:2012-07-17 13:01:17 【问题描述】:如何将UNION
与多个Common Table Expressions
一起使用?
我正在尝试汇总一些汇总数字,但无论我将 ;
放在哪里,我总是会收到错误
SELECT COUNT(*)
FROM dbo.Decision_Data
UNION
SELECT COUNT(DISTINCT Client_No)
FROM dbo.Decision_Data
UNION
WITH [Clients]
AS ( SELECT Client_No
FROM dbo.Decision_Data
GROUP BY Client_No
HAVING COUNT(*) = 1
)
SELECT COUNT(*) AS [Clients Single Record CTE]
FROM Clients;
我很欣赏在上面的示例中我可以将 single CTE 移到开头,但我有一些 CTE 我想UNION
【问题讨论】:
【参考方案1】:如果您尝试合并多个 CTE,则需要先声明 CTE,然后再使用它们:
With Clients As
(
Select Client_No
From dbo.Decision_Data
Group By Client_No
Having Count(*) = 1
)
, CTE2 As
(
Select Client_No
From dbo.Decision_Data
Group By Client_No
Having Count(*) = 2
)
Select Count(*)
From Decision_Data
Union
Select Count(Distinct Client_No)
From dbo.Decision_Data
Union
Select Count(*)
From Clients
Union
Select Count(*)
From CTE2;
您甚至可以使用另一个 CTE:
With Clients As
(
Select Client_No
From dbo.Decision_Data
Group By Client_No
Having Count(*) = 1
)
, CTE2FromClients As
(
Select Client_No
From Clients
)
Select Count(*)
From Decision_Data
Union
Select Count(Distinct Client_No)
From dbo.Decision_Data
Union
Select Count(*)
From Clients
Union
Select Count(*)
From CTE2FromClients;
WITH common_table_expression (Transact-SQL)
【讨论】:
我的错...我想联合多个 CTE @SteveC - 简而言之,您需要先在最终表达式中声明要使用的所有 CTE,然后在联合查询中使用它们。 谢谢。使用逗号来声明多个 CTE 是我所缺少的。【参考方案2】:你可以这样做:
WITH [Clients]
AS ( SELECT Client_No
FROM dbo.Decision_Data
GROUP BY Client_No
HAVING COUNT(*) = 1
),
[Clients2]
AS ( SELECT Client_No
FROM dbo.Decision_Data
GROUP BY Client_No
HAVING COUNT(*) = 1
)
SELECT COUNT(*)
FROM Clients
UNION
SELECT COUNT(*)
FROM Clients2;
【讨论】:
我的错……我想联合多个 CTE 这将不起作用,因为您在声明 Clients2 CTE 后使用 Clients CTE.Its out of reference @AnandPhadke - 这很好用,我不明白你为什么说它不起作用 @DaveShaw -- 是的,我正在考虑在 CTE 之间使用一些 select 语句。如果我们在 CTE 之间有任何 sql 语句,那么它不会起作用。这种情况下它会起作用。以上是关于你如何与多个 CTE 联合?的主要内容,如果未能解决你的问题,请参考以下文章