动态数据透视功能-SQL

时间:2019-02-28 11:52:46

标签: sql sql-server tsql

我遇到一个小问题,我认为这与我的STUFF函数有关。下面的查询提供以下打印,该打印在IN之后的第一列之前带有逗号。

查询:

DECLARE @Columns    nvarchar(max); 
DECLARE @sql        nvarchar(max); 
SET     @Columns = N'' ; 
SELECT  @Columns += N' , p. '+ QUOTENAME(FiscalWeek) 
    FROM 
        (   SELECT FiscalWeek
            FROM MI.dbo.UtilisationSummary_Weekly  
            WHERE   MaxDate > dateadd(ww,-8, getdate())     ) AS x; 

SET @sql = N' SELECT Fee_Earner, '+ STUFF(@columns, 1,2, '') +' 
                FROM    
                        (   SELECT Fee_Earner, WeeklyUtilisation,  FiscalWeek
                            FROM    MI.dbo.UtilisationSummary_Weekly  
                            WHERE   MaxDate > dateadd(ww, -8, getdate() )) AS SourceTable   
                PIVOT   ( Sum(WeeklyUtilisation) FOR FiscalWeek IN (
                            ' + STUFF(REPLACE(@columns, ' p.[', '['), 1 , 1 ,'') +' ) )
                AS p;'; 
PRINT @sql 
EXEC sp_executesql @sql 

打印结果:

SELECT Fee_Earner,  p. [40] , p. [41] , p. [42] , p. [43] , p. [44] , p. [45] , p. [46] , p. [47] , p. [48] 
                FROM    
                        (   SELECT Fee_Earner, WeeklyUtilisation,  FiscalWeek
                            FROM    MI.dbo.UtilisationSummary_Weekly  
                            WHERE   MaxDate > dateadd(ww, -8, getdate() )) AS SourceTable   
                PIVOT   ( Sum(WeeklyUtilisation) FOR FiscalWeek IN (
                            , p. [40] , p. [41] , p. [42] , p. [43] , p. [44] , p. [45] , p. [46] , p. [47] , p. [48] ) )
                AS p;

1 个答案:

答案 0 :(得分:2)

,之前您有一个空格,STUFF在删除空格而不是逗号。

更改下一行

SELECT  @Columns += N' , p. '+ QUOTENAME(FiscalWeek)

SELECT  @Columns += N', p. '+ QUOTENAME(FiscalWeek)