The situation is this:
I have two columns in my database.
User | Parent |
---|---|
Amy K. | Theo K. |
Lena K. | Theo K. |
Jiha L. | John L. |
John L. | Victor L. |
Theo K. | Simba K. |
Simba K. | Ellen K. |
Now I need to make another column using PostgreSQL called Grandparent where I need to put users from the User column in the Grandparent column if they are Parents of the people in the Parent column. So it would look like this:
User | Parent | Grandparent |
---|---|---|
Amy K. | Theo K. | Simba K. |
Lena K. | Theo K. | Simba K. |
Jiha L. | John L. | Victor L. |
John L. | Victor L. | null |
Theo K. | Simba K. | Ellen K. |
Simba K. | Ellen K. | null |
I need to do it directly from the database using SQL and save data in Power BI.
2
Answers
I found the solution:
The table should be self-joined:
Link as a reference: SQL query to get the employee name and their manager name from the same table
You can self-join your table using
LEFT JOIN
to get grandparent (null if not exists).This query fetches the grandparent from the table by joining it with itself twice. The table is aliased as p (for Parent), and gp (for Grandparent). The
LEFT JOIN
statements connect Parent to Grandparent based on column Parent from first alias and User from second alias :Results :
Demo here