2013-03-22 36 views
0

我有以下數據庫表方案,我存儲組織架構。SQL轉換樹到多表的表

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如何才能做到這一點?

+0

對不起,不理解你的問題,這些級別從哪裏來?你能給更多的描述嗎? – ljh 2013-03-22 06:34:25

+0

級別實際上意味着轉換的行號,這也代表組織的層次級別。 – user846741 2013-03-22 07:27:32

+0

[這個問題](http://stackoverflow.com/questions/5314595/sql-server-to-show-a-data-tree-in-a-specific-format)與你非常相似。但請注意(如該問題所示),如果您不知道級別的數量,那麼您需要動態SQL,因此您應該考慮在報告工具或客戶端應用程序中生成輸出,這可能會更容易一些。 – Pondlife 2013-03-22 14:44:25

回答

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/

這基本上給你根據給定的僱員(在這種情況下有4的organizationID)一行,並發現它們的鏈命令。