Question

I have two tables of data that I've joined.

Student 
UPN | Name

and

Subject
UPN | Subject | Result

I have written the following query to bring out a list of all values.

SELECT student.upn,
       subject,
       result
FROM   student
       JOIN subject
         ON subject.upn = student.upn

This results in the following

UPN             Subject       Result
8152760         English       3c
8138130         Spanish       2b
8152760         Spanish       3c
8128500         English       3c
8152760         Mathematics   2b
8152760         French        2b

What I would like to do is have the resultset display for each distinct student a column for each subject, so something like this:

UPN             English      French      Mathematics      Spanish
8152760         3c           2b          2b               3c
8138130         NULL         NULL        NULL             2b
8128500         3c           NULL        NULL             NULL

Ideally I'd like it to auto generate the columns from my subject names, but I'm happy to hardcode them if this is more straightforward.

Was it helpful?

Solution

Here you go:

declare @t as table (UPN int, Subject varchar(50), Result varchar(3))
insert into @t values(8152760, 'English'     ,  '3c')
insert into @t values(8138130, 'Spanish'     ,  '2b')
insert into @t values(8152760, 'Spanish'     ,  '3c')
insert into @t values(8128500, 'English'     ,  '3c')
insert into @t values(8152760, 'Mathematics' ,  '2b')
insert into @t values(8152760, 'French'      ,  '2b')



select distinct t.upn, 
e.Result as Enlish,
s.Result as Spanish,
f.Result as French,
m.Result as Mathematics
from @t t
left join @t e on e.UPN = t.upn and e.Subject = 'English'
left join @t s on s.UPN = t.upn and s.Subject = 'Spanish'
left join @t f on f.UPN = t.upn and f.Subject = 'French'
left join @t m on m.UPN = t.upn and m.Subject = 'Mathematics'

PIVOT version works only with aggregation, that is why I deleted my comment )

SELECT UPN, 
[English]        ,
[Spanish]        ,                       
[Mathematics]    ,
[French]
FROM
(SELECT UPN, Subject, Result 
    FROM @t) AS SourceTable
PIVOT
(
count(Result)
FOR Subject IN ([English]        ,
                [Spanish]        ,                       
                [Mathematics]    ,
                [French])
) AS PivotTable;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top