SQL Server动态PIVOT未正确聚合月度PLD_Value值的问题
问题描述
我有一张TB_Planned表,在SQL Server中执行了以下动态PIVOT查询:
declare @colunas_pivot as nvarchar(max), @comando_sql as nvarchar(max) set @colunas_pivot = stuff(( select distinct ',' + quotename(datename(year,PLD_Date) + '' + datename(month, PLD_Date)) from TB_Planned /* where PLD_Date > getdate() */ order by 1 for xml path('') ), 1, 1, '') print @colunas_pivot set @comando_sql = ' SELECT * FROM ( SELECT [PLD_ProjectSapCode], [PLD_Date], [PLD_Value] FROM TB_Planned ) result_pivot pivot (max(PLD_Value) for PLD_Date in (' + @colunas_pivot + ')) result_pivot ' print @comando_sql execute(@comando_sql)
当前查询结果仅返回每月第一天的PLD_Value数值,我需要实现将PLD_Date按年月进行PIVOT转换,以年月为列分组,展示对应月份PLD_Value的总和。
解决方案
要实现月度分组求和,需从两个核心点修改代码:
- 在子查询中,将原
PLD_Date转换为年月格式的字符串,作为PIVOT的分组依据,而非使用原始日期值; - 将PIVOT中的聚合函数从
MAX改为SUM,实现月度数值求和。
修改后的完整代码如下:
declare @colunas_pivot as nvarchar(max), @comando_sql as nvarchar(max) set @colunas_pivot = stuff(( select distinct ',' + quotename(datename(year,PLD_Date) + ' ' + datename(month, PLD_Date)) from TB_Planned /* where PLD_Date > getdate() */ order by 1 for xml path('') ), 1, 1, '') print @colunas_pivot set @comando_sql = ' SELECT * FROM ( SELECT [PLD_ProjectSapCode], -- 将日期转换为年月格式字符串,作为分组列 datename(year, PLD_Date) + '' '' + datename(month, PLD_Date) as [YearMonth], [PLD_Value] FROM TB_Planned ) result_pivot -- 用SUM替代MAX实现求和,同时将PIVOT的列改为YearMonth pivot (SUM(PLD_Value) for YearMonth in (' + @colunas_pivot + ')) result_pivot ' print @comando_sql execute(@comando_sql)
关键修改说明
- 子查询新增
YearMonth字段:通过datename(year, PLD_Date) + ' ' + datename(month, PLD_Date)将日期转换为类似2024 January的年月格式,确保同一月份的所有记录归为同一组; - PIVOT部分调整:将聚合函数从
MAX(PLD_Value)改为SUM(PLD_Value),同时将for PLD_Date in改为for YearMonth in,与子查询的分组列对应; - 动态列生成:保持与
YearMonth格式一致,确保生成的列名和PIVOT中的分组列匹配。
内容的提问来源于stack exchange,提问作者Guilherme Augusto
相关产品推荐
相关产品推荐

