sql server - SQL Get Total Column from Dynamic Pivot -
i have problem getting total column dynamic pivot query. code got result : the result without total , want total column column 32,33,34,35 , place after column 35 (vertical total column)
here code :
set datefirst 1; declare @cols nvarchar(max), @colnames nvarchar(max), @query nvarchar(max) select @cols = stuff((select distinct ',' + quotename(datepart(wk,oinv.taxdate)) oinv year(oinv.taxdate) = 2016 , month(oinv.taxdate) = 8 xml path(''), type).value('.', 'nvarchar(max)'),1,1,'') select @colnames = stuff((select distinct ', isnull(' + quotename(datepart(wk,oinv.taxdate)) +', 0) '+ quotename(datepart(wk,oinv.taxdate)) oinv year(oinv.taxdate) = 2016 , month(oinv.taxdate) = 8 xml path(''), type).value('.', 'nvarchar(max)'),1,1,'') set @query = 'select salesman, cabang, '+ @colnames +' from(select oslp.slpname salesman, ocrd.u_stem_bp_whse cabang, sum(oinv.doctotal) achiev, datepart(wk,oinv.taxdate) weekno oinv inner join inv1 on inv1.docentry = oinv.docentry inner join oslp on oinv.slpcode = oslp.slpcode inner join oitm on inv1.itemcode = oitm.itemcode inner join omrc on oitm.firmcode = omrc.firmcode inner join ocrd on oinv.cardcode = ocrd.cardcode year(oinv.taxdate) = 2016 , month(oinv.taxdate) = 8 group oslp.slpname, ocrd.u_stem_bp_whse, oinv.taxdate) pivot(sum(achiev) weekno in (' + @cols + ')) pvt order salesman asc' execute(@query);
your appreciated, thank you.
use advice @anton, updated result got : the updated result
change
set @query = 'select salesman, cabang, '+ @colnames +'
to
set @query = 'select salesman, cabang, '+ @colnames +', ' + @sumcol32_35 + '
@subcol32_35 should '[32] + [33] + [34] + [35]'
you can hardcode if column names fixed, or populate inside
select @colnames =
with case ... end statement populate relevant columns only.
Comments
Post a Comment