Dynamic pivot in SQL Server not working as expected

47 views Asked by At

I have the following table: enter image description here

I'm doing a dynamic PIVOT in SQL_Server and I got the following query:

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)

This query results in the following table: enter image description here

As you can see, I want to PIVOT the column "PLD_Date" and group my columns by month/year, and put the sum of the values ​​corresponding to each month, from the column "PLD_Value. However, in this result above it is only returning the value of the first day of each month.

How would I group and correctly add the values ​​of the entire month?

0

There are 0 answers