问题
I have a table with structure and record like this
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 |
-----------------------------------------
How to make a query result with SQL Server like below.
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 |
-------------------------------------------------------------------------------------
回答1:
With table structure as shown, and if number of levels is fixed, you can simply self join multiple times using LIKE on ID column as a join condition:
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+'__'
This should give you the desired output.
来源:https://stackoverflow.com/questions/29793622/sql-server-hierarchy-one-row-to-multiple-column-query