SQL结果从List设置为网格

时间:2014-04-01 11:24:50

标签: sql-server sql-server-2008 list grid resultset

我加入了两个数据表。

Student 
UPN | Name

Subject
UPN | Subject | Result

我编写了以下查询以显示所有值的列表。

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

这导致以下

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

我想要做的是让每个不同学生的结果集显示为每个主题的列,如下所示:

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

理想情况下,我希望自动生成主题名称中的列,但如果这更直接,我很乐意对它们进行硬编码。

1 个答案:

答案 0 :(得分:1)

你走了:

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版仅适用于聚合,这就是我删除评论的原因)

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;