A static version of sql statement should look like:
SELECT var1, var2, var3, [1], [2], COALESCE([1], 0) + COALESCE([2], 0) AS Total
FROM (
SELECT var1, var2, var3, finmonth, Actual_Activity
FROM YOUR_TABLE
WHERE FinYear = 2018) AS DT
PIVOT(SUM(Actual_Activity) FOR finmonth IN ([1], [2])) AS PVT
Now, you have to "convert it" into dynamic version.
If you would like to avoid
NULL
's in
[1]
and
[2]
cols, you can use
COALESCE
method around them.
Note:
FinYear
and
finmonth
should be numeric fields!
[EDIT]
If you would like to get correct data in a
@COLS_SUM
variable, check this:
SELECT @COLS_SUM = @COLS_SUM + 'COALESCE(' + QUOTENAME(finmonth) + ',0)+'
FROM (SELECT DISTINCT finmonth FROM YOUR_TABLE ) AS tmp
SELECT @COLS_SUM = ','+ SUBSTRING(@COLS_SUM, 0, LEN(@COLS_SUM)) +' AS TOTAL'