sql >> Databáze >  >> RDS >> Sqlserver

Hierarchický dotaz v SQL Server 2005

Podívejte se na toto

DECLARE @Table TABLE(
        ID INT,
        ReplacementID INT
)

INSERT INTO @Table (ID,ReplacementID) SELECT 1, NULL
INSERT INTO @Table (ID,ReplacementID) SELECT 2, 3
INSERT INTO @Table (ID,ReplacementID) SELECT 3, NULL
INSERT INTO @Table (ID,ReplacementID) SELECT 4, 5
INSERT INTO @Table (ID,ReplacementID) SELECT 5, 6
INSERT INTO @Table (ID,ReplacementID) SELECT 6, NULL

INSERT INTO @Table (ID,ReplacementID) SELECT 7, 8
INSERT INTO @Table (ID,ReplacementID) SELECT 8, 9
INSERT INTO @Table (ID,ReplacementID) SELECT 9, 10
INSERT INTO @Table (ID,ReplacementID) SELECT 10, NULL

SELECT * FROM @Table

;WITH repl AS (
    SELECT  *, 1 AS Depth
    FROM    @Table t
    UNION   ALL
    SELECT  r.ID,
            t.ReplacementID,
            r.Depth + 1
    FROM    repl r INNER JOIN
            @Table t ON r.ReplacementID = t.ID
    WHERE   t.ReplacementID IS NOT NULL
)
SELECT  repl.ID,
        repl.ReplacementID
FROM    (
            SELECT  ID,
                    MAX(Depth) Depth
            FROM    repl
            GROUP BY ID
        ) Depths INNER JOIN
        repl    ON  Depths.ID = repl.ID
                AND Depths.Depth = repl.Depth
ORDER BY 1



  1. Chyba výjimky Java - Sqlite PrepareStatement.setBlob

  2. Jak mohu vložit více řádků do oracle s hodnotou sekvence?

  3. Chyba MySQL Příliš mnoho připojení

  4. Proč se mi ve sloupci ČÍSLO po formátu zobrazuje ####?