I have used pivot query shown in the following image. I want to show Total in the last colomn. How to achieve it?
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
SELECT @ColumnName = ISNULL(@ColumnName + ',','')+ QUOTENAME(PayHeadName) FROM (SELECT DISTINCT PayHeadName FROM tblPayHeadAssign as pha
inner join tblPayHead as ph on pha.PayHeadID=ph.PayHeadID where BPS='1') AS FeesHead
SET @DynamicPivotQuery = ';WITH CTE AS(SELECT EmpCode,EmpName,EmpFName,t.BPS,PayHeadName,HeadAmount FROM tblPayHeadAssign as pha
inner join tblPayHead as ph on pha.PayHeadID=ph.PayHeadID inner join tblTeacher as t on t.BPS=pha.BPS and EmpStatus=''Active'' )
SELECT EmpCode,EmpName,EmpFName,BPS,'+@ColumnName+'FROM CTE
PIVOT (MAX(HeadAmount)
FOR PayHeadName IN('+@ColumnName+')) p
'
EXEC(@DynamicPivotQuery);