Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Problema di query SQL Server2005

È possibile utilizzare il CTE ricorsivo .

Qualcosa del genere

DECLARE @Table TABLE(
        Supervisorid INT,
        Empid INT
)

INSERT INTO @Table SELECT 3, 4
INSERT INTO @Table SELECT 3, 5
INSERT INTO @Table SELECT 3, 8

INSERT INTO @Table SELECT 4, 9
INSERT INTO @Table SELECT 4, 10
INSERT INTO @Table SELECT 4, 11

INSERT INTO @Table SELECT 8, 12
INSERT INTO @Table SELECT 8, 13

DECLARE @ID INT
SELECT  @ID = 3

;WITH Vals AS (
        SELECT  *
        FROM    @Table
        WHERE   SuperVisorID = @ID
        UNION ALL
        SELECT  v.SuperVisorID,
                t.Empid
        FROM    Vals v INNER JOIN
                @Table t    ON  v.Empid = t.Supervisorid
)
SELECT  SuperVisorID,
        COUNT(Empid) Total
FROM    Vals
GROUP BY    SuperVisorID