Please take a look at this query and provide any suggestions as to turn it into a function. Alternatively putting it into a temp table would work too. Thanks!
DECLARE @cols AS NVARCHAR(MAX)='', @query AS NVARCHAR(MAX)='';
SELECT @cols = @cols + QUOTENAME(learningObjective) + ','
FROM (select distinct learningObjective from XXX where learningObjective <> 'Overall') as tmp
select @cols = substring(@cols, 0, len(@cols))
set @query =
SELECT Student_Name, ' + @cols +', total
select xxx.STUID, s.Student_Name, learningObjective, numberCorrect, total
select STUID, SUM(total) as total
FROM ( select STUID, TESTCODE, learningObjective, numberCorrect , SUM(CASE WHEN numberCorrect > 3 then 1 else 0 end) as total
FROM XXX where learningObjective <> ''Overall'' group by STUID, TESTCODE, learningObjective, numberCorrect ) a group by STUID
ON XXX.STUID = z.STUID
INNER JOIN STU s ON XXX.STUID = s.PID
max(numberCorrect) for learningObjective in (' + @cols + ')