0
votes

I'm currently trying to get the horizontal sum of a report. Currently using dynamic query and a pivot table. Below is my code

declare @cols nvarchar(max) declare @pvt_cols nvarchar(max) declare @sqlquery nvarchar(max)

select @cols= Coalesce(@cols+',','')
    + 'Coalesce([' +MonthYR+ '],0) AS [' + MonthDescription +'] '
            ,@pvt_cols=coalesce(@pvt_cols +',','') +' ['+[MonthYR] +']' 
from @Calendar 
where CASDT between '20110401' and '20111230' (generates column with month headers)

print @cols     
print @pvt_cols
print '--------------------'


Set @sqlquery='Select ProdDesc,'+@cols + ',Total
            from (Select    ProdDesc, 
                    MonthYr, 
                    NetAmount,
                    SUM(NetAmount ) over (partition by ProdDesc) as Total 
            from #Comtempt1
             ) as dat 
                    pivot(
            SUM(NetAmount) for MonthYr in 
            (' + @pvt_cols + '))pvt'

print @sqlquery

exec sp_executesql @sqlquery

I am able to get the total but it shows the total for the whole records whereas I only need to get the total depending on the dates entered by the user.

1

1 Answers

0
votes
declare @cols nvarchar(max) declare @pvt_cols nvarchar(max) declare @sqlquery nvarchar(max)
declare @total nvarchar(max)
select @cols= Coalesce(@cols+',','')
    + 'Coalesce([' +MonthYR+ '],0) AS [' + MonthDescription +'] '
            ,@pvt_cols=coalesce(@pvt_cols +',','') +' ['+[MonthYR] +']' 
            ,@total= Coalesce(@total+'+','') + 'Coalesce([' +MonthYR+ '],0)'
from @Calendar 
where CASDT between '20110401' and '20111230' (generates column with month headers)

print @cols     
print @pvt_cols
print '--------------------'


Set @sqlquery='Select ProdDesc,'+@cols + ',' + @Total + ' Total
            from (Select    ProdDesc, 
                    MonthYr, 
                    NetAmount,
                    SUM(NetAmount ) over (partition by ProdDesc) as Total 
            from #Comtempt1
             ) as dat 
                    pivot(
            SUM(NetAmount) for MonthYr in 
            (' + @pvt_cols + '))pvt'

print @sqlquery

exec sp_executesql @sqlquery