If you use the form of the PIVOT query that looks like
SELECT * FROM
(
) src
PIVOT
(
)
rather than the format you are using then you can easily add the join
--Create the dynamic query with all the values for
--pivot column at runtime
SET @SQLQuery =
N'SELECT * FROM
(SELECT start_time,end_time,subj_name,dd
FROM [dbo].[time_table] tt
INNER JOIN subj s on tt.subjid = s.subjid
) SRC
PIVOT( MAX(subj_name)
FOR dd IN (' + @PivotColumns + ')) AS P'
Notice I'm using
MAX()
rather than
SUM()
to get the course name