I am trying to get a handle on manipulating table data into more visually appealing formats for output. This could be part of the problem as what I want may be intended for separate reporting software.
I have a table that looks like this
teacher student
----------------------
teacher1 Bob
teacher1 Jim
teacher2 Sam
teacher3 Bill
teacher3 John
teacher3 Eric
I want a table that looks something like this:
teacher1 teacher2 teacher3
---------------------------------
Bob Sam Bill
Jim null John
null null Eric
So I tried stuffing all the teacher names in a variable and then using a Pivot
but since I have to choose an aggregate I can only get the Max
or Min
student like this:
DECLARE @teacherList AS VARCHAR(max)
SELECT @teacherList = Stuff((SELECT DISTINCT',[' + teacher + ']'
FROM myTable
FOR xml path('')), 1, 1, '')
DECLARE @dynamic_pivot_query AS VARCHAR(max)
SET @dynamic_pivot_query = 'select' + @teacherList +
'from
(
SELECT [teacher],[student]
FROM [dbo].[myTable]
) as S
Pivot
(
MIN([student])
FOR teacher IN (' + @teacherList + ')
) as P
'
EXEC(@dynamic_pivot_query)
The result of this is:
teacher1 teacher2 teacher3
---------------------------------
Bob Sam Bill
Assuming the following:
- # of teachers and their names are unknown (variable)
- # of students per teacher is unknown and likely different for every teacher
Is there a way to do this?