按列生成带有树路径的视图

时间:2019-02-11 10:47:57

标签: sql-server path tree

我尝试做类似的事情:How can I generate a hierarchy path in SQL that leads to a given node?

我正在使用SQL Server 2016。

我有两个表,第一个,用于父子关系:

CREATE TABLE [TREE] (
[ID_CHILD] varchar(8) NOT NULL,
[ID_PARENT] varchar(8) NULL,
[LEFT_VALUE] numeric(8, 0) NULL,
[RIGHT_VALUE] numeric(8, 0) NULL
)

第一个ID节点是“ ROOT”。 左右值的定义如下:

节点(左,右)

ROOT (0,13)
- A1 (1,6)
-- B1 (2,3)
-- B2 (4,5)
- A2 (7,12)
-- B3 (8,11)
--- C1 (9,10)

ROOT | NULL | 0 | 13
A1   | ROOT | 1 | 6
B1   | A1   | 2 | 3
B2   | A1   | 4 | 5
A2   | ROOT | 7 | 12
B3   | A2   | 8 | 11
C1   | B3   | 9 | 10

每个左右间隔包括所有左右子编号。 我的树的最大深度为10。

第二个,用于影响树中的人力资源:

CREATE TABLE [HR_TREE] (
[ID_HR] varchar(9) NOT NULL,
[ID_NODE] varchar(8) NULL
)

像这样的一些数据:

001664 | A1
001564 | B1
034564 | B1
001224 | C1
001677 | B3

我需要您的帮助来创建显示如下内容的视图:

我的尝试:

如何创建视图[FLAT_HR_TREE] ... ????

ID_HR   | T1   | T2   | T3   | T4   | T5   | T6   | T7   | T8   | T9   | T10
-----------------------------------------------------------------------------
001664  | ROOT | A1   | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL
001564  | ROOT | A1   | B1   | NULL | NULL | NULL | NULL | NULL | NULL | NULL
034564  | ROOT | A1   | B1   | NULL | NULL | NULL | NULL | NULL | NULL | NULL
001224  | ROOT | A2   | B3   | C1   | NULL | NULL | NULL | NULL | NULL | NULL
001677  | ROOT | A2   | B3   | NULL | NULL | NULL | NULL | NULL | NULL | NULL

谢谢您的帮助!

谢谢杰瑞,我已经做到了:

CREATE VIEW MY_FLAT_TREE AS
with CTE_tree
AS
(
  select ht.ID_HR, t.ID_CHILD, t.ID_PARENT, 1 as rank_
  from TREE t
  INNER JOIN HR_TREE ht ON t.ID_CHILD = ht.ID_NODE
  UNION ALL
  select ct.ID_HR, t.ID_CHILD, t.ID_PARENT, rank_ + 1 AS rank_
  from TREE t
  INNER JOIN CTE_tree ct ON ct.ID_PARENT = t.ID_CHILD
)
SELECT ID_HR, [T1], [T2], [T3], [T4], [T5], [T6], [T7], [T8], [T9], [T10]  
FROM (
  SELECT ID_HR, ID_CHILD, 'T'+ CAST(ROW_NUMBER() OVER(PARTITION BY ID_HR order by rank_ DESC) AS VARCHAR(5)) as rank_
  FROM CTE_tree
)up  
PIVOT  
(
  MIN(ID_CHILD) FOR rank_ IN ([T1],[T2],[T3],[T4],[T5],[T6],[T7],[T8],[T9],[T10])
) AS pvt 

1 个答案:

答案 0 :(得分:0)

请为您的问题找到以下解决方案:

with CTE_tree
AS
(
select ht.id_hr, t.id_child, t.id_parent, 1 as rank_
from TREE t
INNER JOIN [THR_TREE] ht ON t.id_child = ht.id_node
UNION ALL
select ct.id_hr, t.id_child, t.id_parent, rank_ + 1 AS rank_
from TREE t
INNER JOIN CTE_tree ct ON ct.id_parent = t.id_child
)
SELECT id_hr, id_child, 'T'+ CAST(ROW_NUMBER() OVER(PARTITION BY id_hr order by rank_ DESC) AS VARCHAR(5)) as rank_
INTO #temp_tree
FROM CTE_tree

select id_hr, [T1], [T2], [T3], [T4], [T5], [T6], [T7], [T8], [T9], [T10]  
FROM (
SELECT id_hr, id_child , rank_ 
FROM #temp_tree )up  
PIVOT  
(
MIN(id_child) FOR rank_ IN ([T1],[T2],[T3],[T4],[T5],[T6],[T7],[T8],[T9],[T10])) AS pvt 
ORDER BY id_hr