0

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

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 中做到这一点?

4

1 回答 1

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)为您提供一行,并找到他们的命令链。

于 2013-03-22T15:11:53.180 回答