创建树形视图

时间:2019-05-09 11:12:55

标签: sql tree

这是我的表结构:

 ID       DepNames
    1         Tron
    11         Milk
    31         Books
    101        Letters
    10101      Lights
    21         Ming
    2100       Pool
    2111       Pool2

我想要得到的是一个树状视图结构:

 ID               DepNames
    1                  Tron
      11               Milk
        101            Letters
           10101       Lights
    21                 Ming
      2100             Pool
           2111        Pool2
    31                 Books

使用SQL select语句是否可能?

1 个答案:

答案 0 :(得分:0)

我在这里模拟了您的问题:https://rextester.com/YPFFLT95570

CREATE TABLE Tree (ID INT, DepName VARCHAR(100), Parent_ID INT);

INSERT INTO Tree VALUES
(0,'Root Node',NULL),
(1,'Tron',0),
(11,'Milk',1),
(31,'Books',0),
(101,'Letters',11),
(10101,'Lights',101),
(21,'Ming',0),
(2100,'Pool',21),
(2111,'Pool2',2100);


WITH cte(ID, DepName, Parent_ID, Level, Sort_Order) AS
(
    SELECT ID, DepName, Parent_ID, 0, CAST(ID AS VARCHAR)
    FROM  
    Tree
    WHERE Parent_ID IS NULL

    UNION ALL

    SELECT child.ID, child.DepName, child.Parent_ID, (parent.Level + 1), CAST((parent.Sort_Order + '/' + CAST(child.ID AS VARCHAR)) AS VARCHAR)
    FROM
    Tree child
    INNER JOIN
    cte parent
    ON
    child.Parent_ID = parent.ID
)
SELECT 
REPLICATE(' ',Level - 1) + CAST(ID AS VARCHAR), DepName
FROM cte 
WHERE DepName <> 'Root Node'
ORDER BY Sort_Order;

老实说,我不明白这个问题背后的原因。尽管这是一个有趣的问题,但我个人认为查询并非旨在缩进。