IF you do a PRINT @SQLPivotQuery
, you will most likely get something like this,[deceased_date], [201801], [201802] as [n1], [n2]
where, in fact, you are looking for something like this,[deceased_date], [201801] AS [n1], [201802] AS [n2]
You need to join your temp tables to get the relationship between [Fund_Mth] and [genericperiod]
Then you need to replace thisSelect @GenericPeriodPivot = Coalesce(@GenericPeriodPivot + ', ','') + quotename(genericperiod)
with something like thisSelect @GenericPeriodPivot = Coalesce(@GenericPeriodPivot + ', ','') + QUOTENAME(Fund_Mth) + ' AS ' + quotename(genericperiod)
Now in your PIVOT statement you need to replace this,[deceased_date],' + @PeriodPivot + ' as ' + @GenericPeriodPivot + '
with something like this,[deceased_date],' + @GenericPeriodPivot + '