这是我的代码:
declare @sql as varchar(max)
set @sql = 'insert into #TempReport select [Country],' + @cols + '
from
(
select
C.Country_Name AS [Country],
D.GSL_Name AS [GSL],
SUM(A.Allocation) AS Total
from Work_Information A
inner join Sales B
on A.Sales_ID = B.Sales_Id
inner join Countries C
on A.Country_ID = C.Country_ID
inner join tbl_GSL D
on A.GSL_ID = D.GSL_ID AND A.Sales_ID = D.Sales_Id
where A.Sales_Id = 1
group by A.Country_ID,C.Country_Name, A.Sales_ID, A.GSL_ID,D.GSL_Name
) P Pivot (sum(Total) for [GSL] in (' + @Cols + ')) as Pvt'
exec(@sql)
declare @SumCols as varchar(max)
select @SumCols = stuff(
(select ', Sum(' + quotename(GSLName) + ')' + REPLACE(GSLName,' ','') from
(
select TOP 200 GSL_Name as GSLName
from tbl_GSL GSL
where Sales_Id = 1
ORDER BY GSL_Name
) GlobalSales
ORDER BY GSLName FOR XML PATH('')
),1,2,'')
declare @sql3 as varchar(1000)
set @sql3 = 'select Country,' + @SumCols + ' from #TempReport group by Country WITH ROLLUP'
exec(@sql3)
我只发布了代码的相关部分,因为存储过程很长。
代码运行正常。我使用WITH ROLLUP子句在最后添加Grand Total行和列。代码的最后一行确实在最后添加了一行,但我还想将最后一列添加为Grand Total。此外,ROLLUP添加的最后一行应该具有第一列值作为总计。