如何创建动态数据透视表 table SQL Server 2008

How to create a dynamic pivot table SQL Server 2008

这就是我的 SQL Server 2008 数据库中的内容,我正在尝试 pivot table 但很难让它工作

Username     Date     hours
--------------------------------------
John       Feb 1995    45
John       Feb 1995    16      
Nancy      March 1998  25
John       May 2001   35.5
Peter      Feb 1995    46
Bill       May 2001    48
Bill       Feb 1995    56

我需要得到这个结果:

UserName   Feb 1995   March 1998   May 2001
--------   --------   ----------   ---------
John        61                      35.5
Nancy                    25
Peter       46
Bill        56                      48
--------------------------------------------
Total       163          25         83.5

基本上我需要从日期列值 (1995-10-01) 中获取所有值并将其作为列的标题,这是动态的取决于 table 中有多少值。

非常感谢任何帮助

首先,一个方法:

create table #tab (
            Username nvarchar(100),
            [Date] date,
            [hours] numeric(8,1)
        )

insert #tab values 
    ('John', '1995-02-01', 45),
    ('John', '1995-02-01', 16),
    ('Nancy', '1998-03-01', 25),
    ('John', '2001-05-01', 35.5),
    ('Peter', '1995-02-01', 46),
    ('Bill', '2001-05-01', 48),
    ('Bill', '1995-02-01', 56)


select  pvt.*
    from (
        select  Username, 
                datename(month, [Date]) + ' ' + convert(nvarchar(20), datepart(year, [Date])) [Date], 
                [hours] 
            from #tab
        ) t
    pivot (
        SUM([hours])
        for [Date] in ([February 1995], [March 1998], [May 2001])
        ) pvt

drop table #tab

现在,您可能需要采用的方式:

create table #tab (
            Username nvarchar(100),
            [Date] date,
            [hours] numeric(8,1)
        )

insert #tab values 
    ('John', '1995-02-01', 45),
    ('John', '1995-02-01', 16),
    ('Nancy', '1998-03-01', 25),
    ('John', '2001-05-01', 35.5),
    ('Peter', '1995-02-01', 46),
    ('Bill', '2001-05-01', 48),
    ('Bill', '1995-02-01', 56)

declare @columns nvarchar(max) = ''
declare @sql nvarchar(max) = ''
declare @delim nvarchar(10) = ''

select  @columns = @columns + @delim + '[' + x.[Date] + ']',
        @delim = ', '
    from (  
        select  datename(month, t.[Date]) + ' ' + convert(nvarchar(20), datepart(year, t.[Date])) [Date],
                datepart(year, t.[Date]) [Year],
                datepart(month, t.[Date]) [Month]
            from #tab t
        ) x
    group by x.[Date]
    order by MAX(x.[Year]), MAX(x.[Month])


select @columns

set @sql = '
    select  pvt.Username,
            ' + @columns + '
        from (
            select  Username, 
                    datename(month, [Date]) + '' '' + convert(nvarchar(20), datepart(year, [Date])) [Date], 
                    [hours] 
                from #tab
            ) t
        pivot (
            SUM([hours])
            for [Date] in (' + @columns + ')
            ) pvt
    '

exec(@sql)

drop table #tab

问题是 PIVOT 不允许您动态指定结果列...您必须知道要旋转的列中有什么才能执行此操作。解决方案是创建具有不同列的动态 SQL,然后基于它构建一个数据透视表。