Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Find and divide the downline into different group

Author  Topic 

JX Choo
Starting Member

2 Posts

Posted - 2014-11-03 : 22:55:31
Hi All,

I want write a sql query to group the member in separate generation..

I have a table like below,

table name: tbmember

column: distno, sponsor, rank

DistNo sponsor rank
-------------------- -------------------------------
1 1 50
2 1 20
3 1 20
4 1 30
5 3 30
6 3 50
7 5 20
8 6 20
9 6 40
10 6 20


If the downline's rank is same or higher than distno 1, then it will move to the next generation

Now distno 6 is same rank with dist 1,
So the result will like this:

Generation 1: 1,2,3,4,5,7

Generation 2: 6,8,9,10



Anyone can help me solve this task? Thanks!

Ifor
Aged Yak Warrior

700 Posts

Posted - 2014-11-04 : 10:00:49
Recursion is the obvious way to approach this:

-- *** Test Data ***
CREATE TABLE #t
(
DistNo int NOt NULL
,sponsor int NOt NULL
,[rank] int NOt NULL
);
INSERT INTO #t
VALUES (1, 1, 50), (2, 1, 20), (3, 1, 20), (4, 1, 30), (5, 3, 30)
,(6, 3, 50), (7, 5, 20), (8, 6, 20), (9, 6, 40), (10, 6, 20);
-- *** End Test Data ***

WITH Generations
AS
(
SELECT ROW_NUMBER() OVER (ORDER BY DistNo) AS Generation
,DistNo, sponsor, [rank]
FROM #t
WHERE [rank] >= (SELECT [rank] FROM #t WHERE DistNo = 1)

UNION ALL

SELECT G.Generation, T.DistNo, T.sponsor, T.[rank]
FROM #t T
JOIN Generations G
ON T.Sponsor = G.DistNo
WHERE T.DistNo <> T.sponsor
AND T.[rank] < (SELECT [rank] FROM #t WHERE DistNo = 1)

)
SELECT Generation, DistNo, sponsor, [rank]
FROM Generations
ORDER BY Generation, DistNo;
Go to Top of Page

JX Choo
Starting Member

2 Posts

Posted - 2014-11-06 : 21:54:50
Hi Ifor,

Thank for your answer.

You help me save a lot of time :)

Have a nice days!
Go to Top of Page
   

- Advertisement -