我在SQL中有以下数据:
现在,我想基于“CostCenterNumber”字段来调整它以获得:
答案 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)
我建议您使用查询中的where
和between
条件