In this answer i asked how to get all subnodes and also having a reference to the root node. Now I realize that I need also the contrary:
I want to have all the nodes and all the parents.
so in this simple tree:
1 - 2 - 3
L - 4 - 5
L - 6
7 - 8
I would like to have
1 1;
2 2;
2 1;
3 3;
3 2;
3 1;
4 4;
4 2;
4 1;
5 5;
5 4;
5 2;
5 1;
6 6;
6 4;
6 2;
6 1;
7 7;
8 8;
8 7;
(the order is not important)
This was the query to obtain the opposite (from parent get all childs). I tried to play with it but couldn't find the solution. Could you suggest?
-- get all childs of all parents
WITH q AS
(
SELECT ID_CUSTOMER, ID_CUSTOMER AS root_customer
FROM CUSTOMERS c
UNION ALL
SELECT c.ID_CUSTOMER, q.root_customer
FROM q
JOIN CUSTOMERS c
ON c.ID_PARENT_CUSTOMER = q.ID_CUSTOMER
)
SELECT *
FROM q