Recursive CTE to find all ancestors OF ALL ITEMS

Herb Caudill

I have a simple hierarchy and need to be able to generate a single table that matches EACH item in the table with ALL of its ancestors. (Caps to emphasize that this is not a duplicate question!)

So here's a table:

Select Item='A', Parent=null into Items union
Select Item='B', Parent='A'  union
Select Item='C', Parent='A'  union
Select Item='D', Parent='B'  union
Select Item='E', Parent='B'  union
Select Item='F', Parent='C'  union
Select Item='G', Parent='C'  union
Select Item='H', Parent='D'  
Go

... which represents this hierarchy:

       A
     /   \
    B     C
   / \   / \
   D E   F G
  /
  H

So B has one ancestor (A), and H has 3 ancestors (D,B,A). This is the desired output:

 Item | Ancestor
 B    | A
 C    | A
 D    | A
 D    | B
 E    | A
 E    | B
 F    | A
 F    | C
 G    | A
 G    | C
 H    | A
 H    | B
 H    | D

Using a recursive CTE, I'm able to find all descendants for any ONE item...

Create Function ItemDescendants(@Item char) Returns @result Table(Item char) As Begin
    ; With AllDescendants as (
        Select
            Item,
            Parent
        From Items i
        Where Item=@Item
        UNION ALL
        Select
            i.Item,
            i.Parent
        from Items i
        Join AllDescendants a on i.Parent=a.Item
    )
    Insert into @result (Item)
    Select Item from AllDescendants
    Where Item<>@Item;
    Return;
End
Go

... but then to get the full expanded list, I have to resort to a cursor (yuk!):

Select Item, Parent into #t From Items

Declare @Item char
Declare c Cursor for (Select Item from Items)
Open c
Fetch c into @Item
While (@@Fetch_Status=0) Begin
    Insert into #t (Item, Ancestor) Select Item, @Item from dbo.ItemDescendants(@Item) 
    Fetch c into @Item
End
Close c
Deallocate c

Select Distinct
    Item,
    Ancestor
From #t
Where Parent is not null
Order by Item,Parent

Drop Table #t

This works, but I would be so much happier if I could do it with a single elegant query. Seems like it should be possible - any ideas?

lc.

Assuming I understand you right, it should be as simple as recursing backwards from the leaf nodes (which is easy since the table Items is storing only the leaf nodes):

;with AncestryTree as (
  select Item, Parent
  from Items
  where Parent is not null
  union all
  select Items.Item, t.Parent  
  from AncestryTree t 
  join Items on t.Item = Items.Parent
 )
select * from AncestryTree
order by Item, Parent

SQL Fiddle demo

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Recursive CTE listing all ancestors as columns

From Dev

The Recursive CTE to query all ancestors of a Parent-Child table is slow

From Dev

SQL Server recursive CTE query to find all items belonging to all categories and their descendants

From Dev

Recursive CTE-Find all Employees Below Manager

From Dev

Recursive CTE-Find all Employees Below Manager

From Dev

recursive cte - mark all leafs

From Dev

PostgreSQL ltree find all ancestors of a given label (not path)

From Dev

Recursive function to find all subgroups

From Dev

How to print all callers ancestors

From Dev

Remove all shorter subsequences containing an ID in a recursive CTE

From Dev

Multiple recursive union all selects in a CTE SQL query

From Dev

Multiple recursive union all selects in a CTE SQL query

From Dev

Recursive query with CTE - Concatenate all fields of child elements and add to parent

From Dev

CakePhp find all is not working along with condition and recursive

From Dev

a recursive java program to find all substring in a string

From Dev

To find infinite recursive loop in CTE

From Dev

Get a set of property values for all ancestors

From Dev

Javascript get ALL ancestors with specific class

From Dev

sql - find items that ALL users have in common

From Dev

How to find items with *all* matching categories

From Dev

MongoDB Tree Model: Get all ancestors, Get all descendants

From Dev

How to get all elements which possibly have ancestors and all their ancestors are without a specified class?

From Dev

Find items in a list that contain all sub-items

From Dev

Find Top level Parent and With Recursive CTE

From Dev

RECURSIVE CTE SQL - Find next available Parent

From Dev

PostgreSQL find all possible combinations (permutations) in recursive query

From Dev

How to make a recursive function for find all Euler path in a graph?

From Dev

Recursive Promise.all?

From Dev

How to list all properties exposed by a Java class and its ancestors in Eclipse?

Related Related

  1. 1

    Recursive CTE listing all ancestors as columns

  2. 2

    The Recursive CTE to query all ancestors of a Parent-Child table is slow

  3. 3

    SQL Server recursive CTE query to find all items belonging to all categories and their descendants

  4. 4

    Recursive CTE-Find all Employees Below Manager

  5. 5

    Recursive CTE-Find all Employees Below Manager

  6. 6

    recursive cte - mark all leafs

  7. 7

    PostgreSQL ltree find all ancestors of a given label (not path)

  8. 8

    Recursive function to find all subgroups

  9. 9

    How to print all callers ancestors

  10. 10

    Remove all shorter subsequences containing an ID in a recursive CTE

  11. 11

    Multiple recursive union all selects in a CTE SQL query

  12. 12

    Multiple recursive union all selects in a CTE SQL query

  13. 13

    Recursive query with CTE - Concatenate all fields of child elements and add to parent

  14. 14

    CakePhp find all is not working along with condition and recursive

  15. 15

    a recursive java program to find all substring in a string

  16. 16

    To find infinite recursive loop in CTE

  17. 17

    Get a set of property values for all ancestors

  18. 18

    Javascript get ALL ancestors with specific class

  19. 19

    sql - find items that ALL users have in common

  20. 20

    How to find items with *all* matching categories

  21. 21

    MongoDB Tree Model: Get all ancestors, Get all descendants

  22. 22

    How to get all elements which possibly have ancestors and all their ancestors are without a specified class?

  23. 23

    Find items in a list that contain all sub-items

  24. 24

    Find Top level Parent and With Recursive CTE

  25. 25

    RECURSIVE CTE SQL - Find next available Parent

  26. 26

    PostgreSQL find all possible combinations (permutations) in recursive query

  27. 27

    How to make a recursive function for find all Euler path in a graph?

  28. 28

    Recursive Promise.all?

  29. 29

    How to list all properties exposed by a Java class and its ancestors in Eclipse?

HotTag

Archive