我目前正在尝试获取报告的水平总和。当前使用动态查询和数据透视表。下面是我的代码
声明@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
我能够获得总数,但它显示了整个记录的总数,而我只需要根据用户输入的日期获得总数。