SQL转换树到多元化表

时间:2013-03-22 06:28:35

标签: sql sql-server tsql

我有以下数据库表方案,我存储组织架构。

OrganizationID   Uniqueidentifier 
ParentID         Uniqueidentifier
Name             String

示例数据:

OrganizationID  Name    ParentID
     1            A 
     2            B        1
     3            C        2

我期待

Level1  Level2  Level3  Level4  Level5
   1      2       3       ...     ...

如何在T-SQL中执行此操作?

1 个答案:

答案 0 :(得分:0)

这会让你得到你想要的东西吗? Sqlfiddle在此设置:http://sqlfiddle.com/#!3/9b107/2

; WITH hierarchy_CTE
AS(
    SELECT OrganizationID, name, parentid, 1 AS Level
    FROM #t1 AS Employee
    WHERE OrganizationID = 4

    UNION ALL

    SELECT boss.OrganizationID, boss.Name, boss.ParentID, Level + 1
    FROM #t1 boss
    INNER JOIN hierarchy_CTE ON boss.OrganizationID = hierarchy_CTE.parentid
    WHERE boss.parentid <> 4 OR boss.parentid IS NULL
  )
, hierarchy2_CTE AS 
(SELECT cte.Level, cte.name
FROM hierarchy_CTE cte)


SELECT * FROM hierarchy2_CTE
PIVOT
(
    MAX(NAME)
    FOR Level IN ([1], [2], [3], [4])
) as pvt

改编自PinalDave的文章:http://blog.sqlauthority.com/2012/04/24/sql-server-introduction-to-hierarchical-query-using-a-recursive-cte-a-primer/

这基本上给你一行基于给定的员工(在这种情况下,其组织ID为4)并找到他们的命令链。