SQL帮助解决动态列分类

时间:2018-03-19 11:05:07

标签: sql-server dynamic grouping pivot-table

我正在使用SQL Server 2012,我有这个WBS结构表:

level   id   parentid   name
================================
1       1    -1         WBS 1      -> root
2       2    1          WBS 1.1    -> child of WBS 1
2       3    1          WBS 1.2    -> child of WBS 1
3       4    2          WBS 1.1.1  -> child of WBS 1.1
3       5    2          WBS 1.1.2  -> child of WBS 1.1
3       6    3          WBS 1.2.1  -> child of WBS 1.2

我需要将ID分类为:

level1   level2   level3   parentid   name
==============================================
1        null     null     -1         WBS 1
null     2        null     1          WBS 1.1
null     3        null     1          WBS 1.2
null     null     4        2          WBS 1.1.1
null     null     5        2          WBS 1.1.2
null     null     6        3          WBS 1.2.1

真正的问题是这个级别是动态的,这意味着该表可以有多于或少于3个级别

我的问题是,这可行吗?也许通过枢轴或其他方式? 在此先感谢:)

1 个答案:

答案 0 :(得分:0)

    declare @ColumnName VARCHAR(max)
    declare @DynamicPivotQuery varchar(max)

--Get  values of the PIVOT Column    
    SET @ColumnName = STUFF((SELECT distinct ',[' + Cast( c.[level] as nvarchar(10))+']'
                FROM Pivot_Example c
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')

--Prepare the PIVOT query using the dynamic 
    set @DynamicPivotQuery = 'SELECT  ' + @ColumnName + ', parentid, [name]  from <br/>(
                    select parentid
                        ,  [name]
                        , id 
                        , [level]
                    from Pivot_Example
               ) x
                pivot 
                (
                     min(ID)
                    for [level] in (' + @ColumnName + ')
                ) p order by parentid'

 --Execute the Dynamic Pivot Query
    execute(@DynamicPivotQuery)

http://sqlhints.com/2014/03/18/dynamic-pivot-in-sql-server/