SQL Pivot查询

时间:2015-01-31 01:12:32

标签: sql tsql pivot-table

我在SQL中有以下数据: enter image description here

现在,我想基于“CostCenterNumber”字段来调整它以获得: enter image description here

2 个答案:

答案 0 :(得分:2)

试试这个:

DECLARE @cols as varchar(max)
DECLARE @sql as varchar(max)

SELECT @cols  = coalesce(@cols  + ',','') + '[' + CostCenterNumber + ']' FROM #MyTable

SET @sql = 
     'SELECT Year, GLClass, Code, GLDescription, ' + @cols + '
       FROM (
             SELECT *
             FROM #MyTable
             ) as P
       PIVOT 
             (
             SUM(Total)FOR [CostCenterNumber] IN (' + @cols + ')
             )AS pvt'

EXEC(@sql)

答案 1 :(得分:1)

我建议您使用查询中的wherebetween条件