Skip to content
Advertisement

Recursive SQL query (parent-child) to include total downline records per record

I have a table that has a parent – child structure.

I managed to bring this structure sorted by creating a field called “Path” with the first name of the agent, so this query:

…returns this, the treeview data:

I tried to do a nested select but it didn’t work. What is the best approach to include the total number of children on each record?

Expected Results:

Thanks.

Advertisement

Answer

OK, one possible way you could do it, not at all sure its the best way though.

  1. Create a new column pathid based on the same principle as your existing path (name), but being unique per person.
  2. Count how many times that id shows up in pathid other than ours by using a sub-query against the CTE.

Returns for your sample data:

PLID sponsorid firstname lastname Status LEVEL path pathid Total Downline
1 0 Danielle Lipsin 1 0 Danielle /1 9
4 1 Alissa Doe 1 1 Danielle/Alissa /1/4 0
2 1 Charles Doe 1 1 Danielle/Charles /1/2 6
6 2 Mark Doe 1 2 Danielle/Charles/Mark /1/2/6 0
5 2 Martin Doe 1 2 Danielle/Charles/Martin /1/2/5 4
8 5 Katy Perry 1 3 Danielle/Charles/Martin/Katy /1/2/5/8 0
7 5 Leo Messi 1 3 Danielle/Charles/Martin/Leo /1/2/5/7 2
9 7 Alex Doe 1 4 Danielle/Charles/Martin/Leo/Alex /1/2/5/7/9 0
10 7 Laureen Doe 1 4 Danielle/Charles/Martin/Leo/Laureen /1/2/5/7/10 0
3 1 Michelle Doe 1 1 Danielle/Michelle /1/3 0
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement