I’m trying to create a query with dynamic columns, based on data from three tables.
This is the database structure:
STUDENT
studentID int,studentNumber int,studentName nvarchar(100).
EXAM:
examID int,examName varchar(100),examenDate datetime,
EXAM_REGISTRATION:
studentID int,examID int,
A record is added to the EXAM_REGISTRATION table when a student has registered for an exam.
What I’m trying to get is a list of all the exams and all the students in a pivot table to see which students have registered for which exams, like this:

Quite frankly I don’t know where to start.
I can query everything individually and put it all together but how can I combine it into one query?
I’ve been researching pivot tables, but every example seems to query only from one table and uses numbers and functions like MIN, AVG etc.
Can someone help me along?
ok lets go
some data to play with
and now the main part, and explanation
first of all you have to get pivot query
as you have it , just change it select statement and studentID list in pivot declaration, you have to generate those parts dynamicly , so we just copy previously written query and replace columns with our token
after that you generate column list and studentID list by concatenting strings in tsql
once you have it , all you have to do is to replace tokens in previous template
and thats it
if you want to read more about pivot go for msdn
if you want to read about dynamic go for this link
edit: to adjust the query for the question from comment you would have to change @sqlColumnList like that