计算SQL Server中动态列的列式总计

时间:2015-03-10 11:28:54

标签: sql sql-server-2008 tsql calculated-columns dynamic-columns

我有以下输出,它是从存储过程生成的,如下所示

   SET @sql = '

   SELECT  * FROM (SELECT [NAMES],logdate,[worked time] 
   from tmp_phys_table GROUP BY NAMES,LOGDATE,[WORKED TIME]) AS [SubTable] 
   PIVOT
   (
    MAX([worked time])
             FOR [logdate] IN ([' + @docDates + '])
       ) AS [Pivot] ;';

以上查询提供以下输出

output datat

现在我想做一个列式总计,并在列的末尾包含一个名为total time的新列,这些列是动态列,例如。可能有3列或30列。

1 个答案:

答案 0 :(得分:1)

应该是这样的:

   SET @sql = '

   SELECT *
   FROM (SELECT [NAMES], logdate, [worked time], [Total Time] 
         FROM tmp_phys_table 
         GROUP BY NAMES,LOGDATE,[WORKED TIME], [Total Time]
         ) AS [SubTable] 
   PIVOT
   (
    MAX([worked time])
             FOR [logdate] IN ([' + @docDates + '])
       ) AS [Pivot] ;';