sql >> データベース >  >> RDS >> Sqlserver

OR条件付きのGROUPBYのようなSQLクエリ

    これは、再帰CTEを使用した完全なソリューションです。

    ;WITH Nodes AS
    (
        SELECT DENSE_RANK() OVER (ORDER BY Part, PartRank) SetId
            , [ID]
        FROM
        (
            SELECT [ID], 1 Part, DENSE_RANK() OVER (ORDER BY [E-mail]) PartRank
            FROM dbo.Customer
            UNION ALL
            SELECT [ID], 2, DENSE_RANK() OVER (ORDER BY Phone) PartRank
            FROM dbo.Customer
        ) A
    ),
    Links AS
    (
        SELECT DISTINCT A.Id, B.Id LinkedId
        FROM Nodes A
        JOIN Nodes B ON B.SetId = A.SetId AND B.Id < A.Id
    ),
    Routes AS
    (
        SELECT DISTINCT Id, Id LinkedId
        FROM dbo.Customer
    
        UNION ALL
    
        SELECT DISTINCT Id, LinkedId
        FROM Links
    
        UNION ALL
    
        SELECT A.Id, B.LinkedId
        FROM Links A
        JOIN Routes B ON B.Id = A.LinkedId AND B.LinkedId < A.Id
    ),
    TransitiveClosure AS
    (
        SELECT Id, Id LinkedId
        FROM Links
    
        UNION
    
        SELECT LinkedId Id, LinkedId
        FROM Links
    
        UNION
    
        SELECT Id, LinkedId
        FROM Routes
    ),
    UniqueCustomers AS
    (
        SELECT Id, MIN(LinkedId) UniqueCustomerId
        FROM TransitiveClosure
        GROUP BY Id
    )
    SELECT A.Id, A.[E-mail], A.Phone, B.UniqueCustomerId
    FROM dbo.Customer A
    JOIN UniqueCustomers B ON B.Id = A.Id
    


    1. SQL Server2014CTP1での優先度の低いロック待機オプションの調査

    2. Herokuの永続的なデータベースクレデンシャル

    3. MySQLで先頭と末尾の空白を削除する方法

    4. AWSのKubernetesクラスターからPostgresRDSにアクセスする