简体   繁体   English

如何使用SQL Server 2008的层次结构ID创建祖先的累积“派生”列

[英]How do you create a cumulative, “derived” column of ancestry using SQL Server 2008 hierarchyid

Imagine your typical manager / employee hierarchy, where you have an employee with a boss, who in turn has a boss, who in turn has a boss. 想象一下您的典型经理/员工层次结构,其中您的员工中有老板,而老板又有老板,而老板又有老板。

How would you write a query that would have a column with, say, all the boss's names as a varchar. 您将如何编写一个查询,该查询的列将以所有老板的名字作为varchar。

Given this data (leaving out the hierarchyid column but the id column here essentially describes that column): 给定此数据(省去了architectureid列,但此处的id列实质上描述了该列):

id | name          | bossid
1  | BigBoss       | 0
2  | CTO           | 1
3  | CTO Lackey    | 2
4  | CIO           | 1
5  | CIO Lackey    | 4

End up with this resultset: 最后得到这个结果集:

id | name          | all boss names
1  | BigBoss       |
2  | CTO           |Big Boss
3  | CTO Lackey    |Big Boss, CTO
4  | CIO           |Big Boss
5  | CIO Lackey    |Big Boss, CIO

Thanks! 谢谢!

Since you're on SQL 2008: 由于您使用的是SQL 2008:

;WITH CTE_Tree AS
(
    SELECT
        id,
        name,
        '' AS boss_names
    FROM
        My_Table
    WHERE
        boss_id IS NULL
    UNION ALL
    SELECT
        T.id,
        T.name,
        CTE.boss_names + ', ' + CTE.name
    FROM
        CTE_Tree CTE
    INNER JOIN My_Table T ON
        T.boss_id = CTE.id
)
SELECT
    id,
    name,
    boss_names
FROM
    CTE_Tree

This is off the top of my head, so you may need to tweak it. 这不在我的脑海中,因此您可能需要对其进行调整。 It will have an extra comma at the start of the boss_names. boss_names的开头将带有一个逗号。 You can either remove that in your final query, or put in a check of CTE.boss_names in the CTE to decide whether or not to prepend the comma. 您可以在最终查询中将其删除,也可以在CTE中检查CTE.boss_names来决定是否在逗号前加上逗号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM