sql >> Database >  >> RDS >> Sqlserver

Recursieve query in SQL Server

Probeer dit:

;WITH CTE
AS
(
    SELECT DISTINCT
        M1.Product_ID Group_ID,
        M1.Product_ID
    FROM matches M1
        LEFT JOIN matches M2
            ON M1.Product_Id = M2.matching_Product_Id
    WHERE M2.matching_Product_Id IS NULL
    UNION ALL
    SELECT
        C.Group_ID,
        M.matching_Product_Id
    FROM CTE C
        JOIN matches M
            ON C.Product_ID = M.Product_ID
)
SELECT * FROM CTE ORDER BY Group_ID

U kunt OPTION(MAXRECURSION n) . gebruiken om de recursiediepte te regelen.

SQL FIDDLE DEMO



  1. MySQL verleent alle privileges aan de database behalve één tabel

  2. Oracle krijgt externe sleutels

  3. postgresql-poortverwarring 5433 of 5432?

  4. Werken met niet-ASCII JDBC-gegevens in Talend