views:

34

answers:

1

i have a table which contains the following fields

  • Supervisorid
  • Empid

This is just like a referral program. A guy can refer 3 guys under him i.e, 3 is referring three guys namely 4 5 8 similarly 4 is referring 9 10 and 11 likewise 8 is referring 12, 13 it goes like this..

I want a query to get the total no of down line members under a guy say 3

+2  A: 

You can make use of Recursive CTE.

Something like this

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
astander