动态列的水平和

时间:2012-11-29 21:28:19

标签: sql-server dynamic pivot-table

我目前正在尝试获取报告的水平总和。目前使用动态查询和数据透视表。以下是我的代码

声明@cols nvarchar(max) 声明@pvt_cols nvarchar(max) 声明@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

我能够得到总数,但它显示了整个记录的总数,而我只需要根据用户输入的日期得到总数。

1 个答案:

答案 0 :(得分:0)

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