web-dev-qa-db-ja.com

複数のCTEをどのように結合しますか?

複数のCommon Table ExpressionsUNIONをどのように使用しますか?

サマリー番号をまとめようとしていますが、;をどこに置いても、常にエラーが発生します

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;

PDATE:上記の例ではsingle CTEを先頭に移動できますが、UNIONにしたいCTEがいくつかあります

46
SteveC

複数の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)

82
Thomas

次のようにできます:

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;
13
DaveShaw