Skip to content
Advertisement

SQL Server hierarchy, selecting parent nodes for distinct IDs

Stuck on this hierarchy problem, so here goes. I have the following hierarchy table, which has been truncated.

HierarchyIDs

The hierarchy has been joined to another table on the ‘codes’ column, with the following sample result. Let’s call this table1.

table with hierarcjy

For each distinct ID in table1, I want to utilize the hierarchy to find a parent, if it exists. For example, under the codes column, 18 is the parent of 19. I would like to fold or group the 19 with 18 and eliminate that row. The desired result is something like this.

desired result

This does sort of what I want, using the GetAncestor method:

SELECT A.OrgNode, A.Codes, A.ID, B.OrgNode, B.Codes, B.ID FROM table1 A INNER JOIN table1 B ON A.OrgNode.GetAncestor(1) = B.OrgNode WHERE A.ID = B.ID

Advertisement

Answer

This self-join, with the GetAncestor function, did what I wanted it to do, with the ‘where’ on the same ID.

SELECT A.OrgNode, A.Codes, A.ID, B.OrgNode, B.Codes, B.ID FROM table1 A INNER JOIN table1 B ON A.OrgNode.GetAncestor(1) = B.OrgNode WHERE A.ID = B.ID

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement