动态转动到列 - SQL

时间:2014-11-05 22:36:24

标签: sql sql-server pivot-table

/****** Script for SelectTopNRows command from SSMS  ******/

declare @ActivityYear int = 2014
declare @ActivityYear1 int = 2015
declare @ActivityMonth int = 1
declare @ActivityMonth1 int = 3


Select FinancialCategory, ID, (CONVERT(varchar(5), ActivityMonth) + '-' 
   + CONVERT(varchar(5), ActivityYear)) As [Month-Year], Sum(HoursCharged) As [Hours]
FROM Forecast
where (ActivityMonth between @ActivityMonth and @ActivityMonth1)
            AND (ActivityYear between @ActivityYear and @ActivityYear1)
            AND FinancialCategory = 'Forecast'

Group By FinancialCategory, ID,ActivityMonth, ActivityYear 

这输出一个如下所示的表: enter image description here

我想转移它,以便按范围内的日期划分每个ID的小时数。注意:这个日期范围是动态的,我设置初始日期用于测试目的。 enter image description here

1 个答案:

答案 0 :(得分:1)

我最近学到了一些关于动态支点的知识,this post帮了很多忙。作为一种练习,我转换了你的,我认为这看起来像这样,但是没有经过测试,因为我现在没有时间来制作桌子等。 HTH。

declare @ActivityYear int = 2014
declare @ActivityYear1 int = 2015
declare @ActivityMonth int = 1
declare @ActivityMonth1 int = 3

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)       

select @cols = STUFF((SELECT distinct ',' + QUOTENAME((CONVERT(varchar(5), ActivityMonth) + '-' 
                + CONVERT(varchar(5), ActivityYear)))
            FROM Forecast
            WHERE (ActivityMonth between @ActivityMonth and @ActivityMonth1)
                AND (ActivityYear between @ActivityYear and @ActivityYear1)
                AND FinancialCategory = 'Forecast'
        FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT FinancialCategory, ID, ' + @cols + ' FROM
             (
                SELECT FinancialCategory, ID, (CONVERT(varchar(5), ActivityMonth) + ''-'' 
                    + CONVERT(varchar(5), ActivityYear)) As [Month-Year],HoursCharged
                FROM Forecast
                WHERE (ActivityMonth between ' + @ActivityMonth + ' and ' + @ActivityMonth1 + ')
                            AND (ActivityYear between ' + @ActivityYear + ' and ' +  
                            @ActivityYear1 + ')
                            AND FinancialCategory = ''Forecast'' 
            ) x
            PIVOT 
            (
                Sum(HoursCharged)
                for (CONVERT(varchar(5), ActivityMonth) + ''-''
                    + CONVERT(varchar(5), ActivityYear)) in (' + @cols + ')
            ) p '

execute(@query)