一个表中的多个父子树。从节点值

时间:2018-05-24 09:02:02

标签: sql-server common-table-expression

我有一张包含三棵树的表:

   T1      T2      T3     T4
   --      --      --     --

   A       F       B      H
  |  |    |  |    |  |    |
  B  C    B  C    A  C    I
 | |      |               |
 D E      D               B
 |                        |
 G                        J

我希望能够让distinct个节点位于特定节点值下。

B D, E, G DA, CJdistinct,其中A, C, D, E, G, J为{{1} }}

declare @t table (t_id int, parent_t_id int, tree varchar(2), item varchar)

insert into @t

select 1, 0, 'T1', 'A' union 
select 2, 1, 'T1', 'B' union 
select 3, 1, 'T1', 'C' union 
select 4, 2, 'T1', 'D' union 
select 5, 2, 'T1', 'E' union 
select 5, 4, 'T1', 'G' union 

select 6, 0, 'T2', 'F' union 
select 7, 6, 'T2', 'B' union 
select 8, 6, 'T2', 'C' union 
select 9, 7, 'T2', 'D' union 

select 10, 0,  'T3', 'B' union 
select 11, 10, 'T3', 'A' union 
select 12, 10, 'T3', 'C' union

select 13, 0,  'T4', 'H' union 
select 14, 13, 'T4', 'I' union 
select 15, 14, 'T4', 'B' union
select 16, 15, 'T4', 'J' 

select * from @t

我怀疑需要CTE吗?

2 个答案:

答案 0 :(得分:2)

试试这个:

;with cte as
    (

        Select t1.* From @t t1
        JOIN @t t2 on t1.parent_t_id=t2.t_id AND t1.tree=t2.tree
        Where t2.item =@Item

        Union All

        Select t1.* From @t t1
        JOIN cte t2 on t1.parent_t_id=t2.t_id AND t1.tree=t2.tree       
    )

    Select  DISTINCT Item FROM cte

答案 1 :(得分:0)

是的,CTE可以是一个选项

SELECT * FROM @t ORDER BY t_id 
;WITH myCTE (Id, ParentId,Item)
AS
(SELECT  t_Id ,Parent_t_Id ,Item
 FROM  @t
 UNION ALL
 SELECT  t_Id ,Parent_t_Id ,t1.Item
 FROM @t t1
 INNER JOIN myCTE tmp ON tmp.ParentId    = t1.t_Id
 )

 SELECT DISTINCT * FROM myCTE ORDER BY parentId