2017-05-04 49 views
3

我对SQL比较陌生。目前,我有以下CoursesTbl没有最小和最大值的SQL聚合

StudentName  CourseID  InstructorName 
    Harry Potter  180  John Wayne 
    Harry Potter  181  Tiffany Williams 
    John Williams 180  Robert Smith 
    John Williams 181  Bob Adams 

现在我真正想要的是这样的:

StudentName  Course1(180)  Course2(181) 
Harry Potter John Wayne  Tiffany Williams 
John Williams Robert Smith Bob Adams 

我已经试过此查询:

Select StudentName, Min(InstructorName) as Course1, Max(InstructorName) as 
Course2 from CoursesTbl 
Group By StudentName 

现在很明显,我认为我需要按学生姓名分组。但是使用Min和Max混淆了教师的顺序。

即闵哈利是约翰·韦恩和Max是蒂凡尼·威廉姆斯
民为约翰·威廉姆斯是鲍勃·亚当斯和Max是罗伯特·史密斯。

因此,它不以正确的顺序显示教师。

任何人都可以请建议如何解决这个问题吗?

+0

你需要的不是一个聚合函数,而是'PIVOT'。看看[这里](https://blogs.msdn.microsoft.com/spike/2009/03/03/pivot-tables-in-sql-server-a-simple-sample/) –

回答

4

可以使用条件聚合与聚合函数沿着CASE语句将数据PIVOT成列:

select 
    [StudentName], 
    Course1 = max(case when CourseId = 180 then InstructorName end), 
    Course2 = max(case when CourseId = 181 then InstructorName end) 
from #Table1 
group by StudentName 

Demo。您也可以使用PIVOT功能获得结果:

select 
    StudentName, 
    Course1 = [180], 
    Course2 = [181] 
from 
(
    select StudentName, 
    CourseId, 
    InstructorName 
    from #Table1 
) d 
pivot 
( 
    max(InstructorName) 
    for CourseId in ([180], [181]) 
) piv 

另一个Demo

+1

使用case子句有完成了这个把戏。因为我的课程ID已经预先知道为180或181,这非常好。谢谢! – paratrooper

+0

很高兴它为你工作,如果你确实有'courseIDs'数量未知,那么你必须看看使用动态SQL来获得相同的结果。 – ollie