对于以下sql脚本,我想添加一个" Total"末尾的列,用于对每行的列中的数据求和。
请帮助:
select * from
(SELECT Calender.YrPer, [Period DATA 6b].PRODUCT_NO, isnull(sum([Period DATA 6b].LI_QTY+[Period DATA 6b].RG_QTY*1.0),0) as "TotalUnits"
FROM Calender INNER JOIN
[Period DATA 6b] ON Calender.[Starting Period] = [Period DATA 6b].STARTING_PERIOD LEFT OUTER JOIN
Allproducts ON [Period DATA 6b].PRODUCT_NO = Allproducts.PRODUCT_NO
where Calender.YrPer >= '2012P05'
group by Calender.YrPer, [Period DATA 6b].PRODUCT_NO)
as test1
pivot
(
sum(TotalUnits)
for YrPer
in ([2012P05],[2012P06],[2012P07],[2012P08],[2012P09],[2012P10],[2012P11],[2012P12],[2012P13],[2013P01],[2013P02],[2013P03],[2013P04],[2013P05],[2013P06],[2013P07],[2013P08],[2013P09],[2013P10],[2013P11],[2013P12],[2013P13],[2014P01],[2014P02],[2014P03],[2014P04])
)
PivotTable
order by PRODUCT_NO
样本所需的输出:
PRODUCT_NO 2012P05 2012P06 2012P07 2012P08 2012P09 2012P10 2012P11 2012P12 2012P13 2013P01 2013P02 2013P03 2013P04 2013P05 2013P06 2013P07 2013P08 2013P09 2013P10 2013P11 2013P12 2013P13 2014P01 2014P02 2014P03 2014P04 2013 R52 2014 R52
75 551 506 473 261 557 1037 285 250 278 234 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 4432 0
174 NULL NULL NULL NULL 1 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 1 0
216 NULL NULL 0 0 0 0 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 0 0
答案 0 :(得分:1)
使用您的代码,添加union plus查询以仅通过PRODUCT_NO获取总计组。 YrPer设置为常数" TotalPerProduct"并在枢轴中使用此常量。 由于您未包含任何样本数据。我刚刚添加了代码,我认为它应该可行。
试试..
select * from
(SELECT Calender.YrPer, [Period DATA 6b].PRODUCT_NO, isnull(sum([Period DATA 6b].LI_QTY+[Period DATA 6b].RG_QTY*1.0),0) as "TotalUnits"
FROM Calender INNER JOIN
[Period DATA 6b] ON Calender.[Starting Period] = [Period DATA 6b].STARTING_PERIOD LEFT OUTER JOIN
Allproducts ON [Period DATA 6b].PRODUCT_NO = Allproducts.PRODUCT_NO
where Calender.YrPer >= '2012P05'
group by Calender.YrPer, [Period DATA 6b].PRODUCT_NO
UNION
SELECT 'TotalPerProduct' YrPer, [Period DATA 6b].PRODUCT_NO, isnull(sum([Period DATA 6b].LI_QTY+[Period DATA 6b].RG_QTY*1.0),0) as "TotalUnits"
FROM Calender INNER JOIN
[Period DATA 6b] ON Calender.[Starting Period] = [Period DATA 6b].STARTING_PERIOD LEFT OUTER JOIN
Allproducts ON [Period DATA 6b].PRODUCT_NO = Allproducts.PRODUCT_NO
where Calender.YrPer >= '2012P05'
group by [Period DATA 6b].PRODUCT_NO
)
as test1
pivot
(
sum(TotalUnits)
for YrPer
in ([2012P05],[2012P06],[2012P07],[2012P08],[2012P09],[2012P10],[2012P11],[2012P12],[2012P13],[2013P01],[2013P02],[2013P03],[2013P04],[2013P05],[2013P06],[2013P07],[2013P08],[2013P09],[2013P10],[2013P11],[2013P12],[2013P13],[2014P01],[2014P02],[2014P03],[2014P04], [TotalPerProduct])
)
PivotTable
order by PRODUCT_NO