CTE получить root-имя - PullRequest
       20

CTE получить root-имя

0 голосов
/ 29 июня 2019

У меня очень простой стол, но я борюсь с CTE:

ID | Parent | Name
---+--------+---------
 1 | NULL   | Root
 2 |   1    | Child1
 3 |   2    | Child2

Я бы хотел получить такой результат:

Element | Root
--------+------
Root    | Root
Child1  | Root
Child2  | Root

Мой CTE - что-то вроде этого ...

WITH cte AS
(
    SELECT a.id, a.parent, a.name, 1 as lvl
    FROM table1 a

    UNION ALL

    -- Perform the recursive join
    SELECT a.id, a.parent, a.name, Lvl+1 AS Lvl
    FROM table1 a
    INNER JOIN cte pa ON cte.parent = a.id
)
SELECT * 
FROM cte 

Теперь я бы агрегировал (max) и (self) соединение, но это вроде плохо / неправильно.

Ответы [ 2 ]

2 голосов
/ 29 июня 2019

Это немного сложно, потому что вы пересекаете идентификаторы, но, в конце концов, вам просто нужны имена. Следующее обрабатывает это путем поиска имен после рекурсивный CTE нашел корневые идентификаторы:

with cte as (
      select id, parent, name, 1 as lev
      from t
      union all
      select cte.id, t.parent, cte.name, lev + 1
      from cte join
           t
           on t.id = cte.parent
      where t.parent is not null
     )
select top (1) with ties cte.name, coalesce(tparent.name, cte.name) as root
from cte left join
     t tparent
     on tparent.id = cte.parent
order by row_number() over (partition by cte.id order by cte.lev desc)

Здесь - это дБ <> скрипка.

1 голос
/ 29 июня 2019

Попробуйте

  with cte as (
      select id, parent, name, name as root
      from t
      where parent is null     
      union all
      select t.id, t.parent, t.name, cte.root
      from cte 
      join t on t.parent = cte.id
  )
  select name, root
  from cte
...