I need your help with this query I can’t solve.
Here’s the thing, let’s say I have a table like this:
Father | Son
1 | 2
1 | 3
1 | 4
3 | 5
3 | 6
2 | 7
4 | 8
5 | 9
6 | 10
So as you can see the table represents a father-son relationship, I need to find all the sons (and the sons of the sons) of one father, for example if Im looking for the sons of number 1 we will get a table like this
Father | son
1 | 2
1 | 3
1 | 4
1 | 5
1 | 6
1 | 7
1 | 8
1 | 9
1 | 10
If I’m lookeing for the sons of the number 3 we will get:
Father | son
3 | 5
3 | 6
3 | 9
3 | 10
okay I think you understood my point. The next problem is that I have to do it for each father in the table. So at the end, the table will be as follows:
Father | son
1 | 2
1 | 3
1 | 4
1 | 5
1 | 6
1 | 7
1 | 8
1 | 9
1 | 10
3 | 5
3 | 6
3 | 9
3 | 10
2 | 7
4 | 8
5 | 9
6 | 10
is pretty similar to go over a tree.
I have been trying to figure out this query for a while with not success. I did a code like this
WITH son
AS (
-- in
SELECT FK_CC_B
FROM PG_Rols_CC
WHERE FK_CC_A = @idCC
UNION ALL
--recur
SELECT t.FK_CC_B
FROM PG_Rols_CC AS t
JOIN hijos AS a
ON t.FK_CC_A = a.FK_CC_B
)
insert into @TableSons (idSon) SELECT * FROM son
But it doesn’t works for each father at the same time and the resulting table is a little bit different, it only has the son ID. Example
son
3
4
5
6
7
Hope you can help me.
If you want to get the descendents of all fathers, you need to get rid of the
WHEREclause in the first part of your Common Table Expression (CTE).If you want to output two columns (Father and Descendent), you need to add these columns to both parts of the CTE.
Like this: