0

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
  • Consider re-wording/formatting your question. Very difficult to understand. Commented Oct 22, 2010 at 4:42
  • Thanks @OMG Ponies. :) Still hard to understand the second paragraph tho (not because of formatting, but because of poor wording). Commented Oct 22, 2010 at 4:43

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.