0

I have Organizations table:

Id  Name  ParentId
------------------
 1  Org1         5
 2  Org2         5
 3  Org3         4
 4  Depart2      6
 5  Depart1      6
 6  Company   null

What I would like to achieve is query which returns table with belonging of each organization to higher order organization units up in hierarchy tree:

Id    BelongsToOrgId
1     1                  Org1 is part of Org1
1     5                  Org1 is part of Depart1  
1     6                  Org1 is part of Company
2     2                  Org2 is part of Org2
2     5                  Org2 is part of Depart1
2     6                  Org2 is part of Company
3     3                  Org3 is part of Org3
3     4                  Org3 is part of Depart2
3     6                  Org3 is part of Company
4     4                  Depart2 is part of Depart2 
4     6                  Depart2 is part of Company 
5     5                  Depart1 is part of Depart1  
5     6                  Depart1 is part of Company
6     6                  Company is part of Company

Best Regards, Piotr

0

2 Answers 2

2
WITH RECURSIVE
cte AS ( SELECT Id, Name, id BelongsToOrgId, Name UpperName
         FROM Organizations 
       UNION ALL
         SELECT Organizations.Id, Organizations.Name, cte.BelongsToOrgId, cte.Name
         FROM Organizations 
         JOIN cte ON Organizations.ParentId = cte.Id )
SELECT Id, BelongsToOrgId, CONCAT(Name, ' is part of ', UpperName) Relation
FROM cte
ORDER BY Id, BelongsToOrgId;

fiddle

Sign up to request clarification or add additional context in comments.

Comments

0

Thanks Akina,

We are almost there, one fix:

WITH RECURSIVE
cte AS ( SELECT Id, Name, id BelongsToOrgId, Name UpperName
         FROM Organizations 
       UNION ALL
         SELECT Organizations.Id, Organizations.Name, cte.BelongsToOrgId, cte.UpperName
         FROM Organizations 
         JOIN cte ON Organizations.ParentId = cte.Id )
SELECT Id, BelongsToOrgId, CONCAT(Name, ' is part of ', UpperName) Relation
FROM cte
ORDER BY Id, BelongsToOrgId;

It is cte.UpperName and not cte.Name in line 5

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.