69

你如何使用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;

我很欣赏在上面的示例中,我可以将单个CTE 移到开头,但我有许多 CTE 我想UNION

4

2 回答 2

118

如果您尝试合并多个 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)

于 2012-07-18T13:17:40.350 回答
14

你可以这样做:

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;
于 2012-07-18T13:18:26.370 回答