SQL 服务器层次结构单行多列查询

SQL Server hierarchy one row to multiple column query

我有一个 table 结构和记录是这样的

ID          | Name                      |
-----------------------------------------
01          | Group Category            |
0101        | Category One              |
010101      | Category One Sub          |
01010101    | Category One Sub Sub      |
010102      | Category One Sub Two      |
01010201    | Category One Sub Sub Two  |
0102        | Category Two              |
010201      | Category Two Sub          |
01020101    | Category Two Sub Sub      |
0103        | Category Three            |
010301      | Category Three Sub        |
01030101    | Category Three Sub Sub    |
-----------------------------------------

如何使用如下所示的 SQL 服务器生成查询结果。

Column1         | Column2       | Column3               | Column4                   |
-------------------------------------------------------------------------------------
Group Category  | Category One  | Category One Sub      | Category One Sub Sub      |
-------------------------------------------------------------------------------------
Group Category  | Category One  | Category One Sub Two  | Category One Sub Sub Two  |
-------------------------------------------------------------------------------------
Group Category  | Category Two  | Category Two Sub      | Category Two Sub Sub      |
-------------------------------------------------------------------------------------
Group Category  | Category Three| Category Three Sub    | Category Three Sub Sub    |
-------------------------------------------------------------------------------------

具有如图所示的table结构,如果级别数固定,您可以简单地使用ID列上的LIKE作为连接条件自行连接多次:

select t1.name, t2.name, t3.name, t4.name
from #t t4
join #t t3 on t4.id like t3.id+'__'
join #t t2 on t3.id like t2.id+'__'
join #t t1 on t2.id like t1.id+'__'

这应该会给你想要的输出。