You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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的总和。

解决方案

要实现月度分组求和,需从两个核心点修改代码:

  1. 在子查询中,将原PLD_Date转换为年月格式的字符串,作为PIVOT的分组依据,而非使用原始日期值;
  2. 将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 07:05:19