mssql层次结构一行到多列查询

时间:2015-04-22 07:35:23

标签: sql-server hierarchy

我有一个结构和记录表,如下

________________________________________
ID          | Name              |
-----------------------------------------
01          | Group Category    |
0101        | Category      |
010101      | Category Sub      |
01010101    | Category Sub Sub  |
-----------------------------------------

如何使用像bellow这样的mssql创建查询结果。

Column1         | Column2       | Column3       | Column4           |
-------------------------------------------------------------------------
Group Category  | Category Sub  | Category Sub  | Category Sub Sub  |
-------------------------------------------------------------------------

2 个答案:

答案 0 :(得分:1)

declare @t table (ID varchar(10),name varchar(20))
insert into @t (ID,name) values ('01','Group Category'),('0101','Category'),
('010101','Category Sub'),('01010101','Category Sub Sub ')



select 
MAX(case when ID = '01' THEN name ELSE '' END )AS Column1,
MAX(case when ID = '0101' THEN name ELSE '' END )AS Column2,
MAX(case when ID = '010101' THEN name ELSE '' END )AS Column3,
MAX(case when ID = '01010101' THEN name ELSE '' END )AS Column4 
from @t

答案 1 :(得分:0)

你也可以像这样偷看你的桌子:

SELECT [1] AS Column1, [2] AS Column2, [3] AS Column3, [4] AS Column4
FROM
(
    SELECT 
        Name, 
        ROW_NUMBER() OVER(ORDER BY ID) Seq 
    FROM [Table]
) t
PIVOT
(
    MAX(Name)
    FOR Seq IN ([1], [2], [3], [4])
) p