Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

Problème de requête SQL Server2005

Vous pouvez utiliser la récursivité CTE .

Quelque chose comme ça

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