SQL Server:将表联接到自身以水平显示数据

时间:2019-05-27 08:31:49

标签: sql sql-server

我有一张表格,其中包含学生成绩(学生ID,科目,年份,成绩)。

我想水平显示同一学生,科目但不同年份的成绩。

我遇到的问题是,并非所有年份的所有科目都可用,我的意思是学生每年可以选修不同的科目。我想将它们全部水平显示在一张桌子上。

示例:

image 1

我尝试了此查询

SELECT TOP (100) PERCENT 
    dbo.New_Portal_OldMarks.StudentID, dbo.New_Portal_OldMarks.[Student Name], 
    dbo.New_Portal_OldMarks.SubjectName, dbo.New_Portal_OldMarks.AcademicYear, 
    dbo.New_Portal_OldMarks.Class, dbo.New_Portal_OldMarks.Term1, dbo.New_Portal_OldMarks.Term2, 
    dbo.New_Portal_OldMarks.Term3, dbo.New_Portal_OldMarks.Final, 
    New_Portal_OldMarks_1.AcademicYear AS AcademicYear2, 
    New_Portal_OldMarks_1.Class AS Class2, 
    New_Portal_OldMarks_1.Term1 AS [Term1-2], 
    New_Portal_OldMarks_1.Term2 AS [Term2-2], 
    New_Portal_OldMarks_1.Term3 AS [Term3-2], 
    New_Portal_OldMarks_1.Final AS [Final-2]
FROM
    dbo.New_Portal_OldMarks 
FULL OUTER JOIN
    dbo.New_Portal_OldMarks AS New_Portal_OldMarks_1 ON dbo.New_Portal_OldMarks.StudentID = New_Portal_OldMarks_1.StudentID 
                                                     AND dbo.New_Portal_OldMarks.SubjectName = New_Portal_OldMarks_1.SubjectName
WHERE     
    (dbo.New_Portal_OldMarks.StudentID = 1004000)
ORDER BY 
    AcademicYear2

我尝试了所有联接查询(例如JOIN,LEFT JOIN,RIGHT JOIN等),但是所有联接返回错误的结果

1 个答案:

答案 0 :(得分:0)

您可以使用条件聚合:

SELECT om.ID, om.StudentID, om.[Student Name], om.SubjectName,
       MAX(CASE WHEN om.class = 11 THEN academicyear END) as academicyear,
       MAX(CASE WHEN om.class = 11 THEN class END) as class,
       MAX(CASE WHEN om.class = 11 THEN term1 END) as term1,
       MAX(CASE WHEN om.class = 11 THEN term2 END) as term2,
       MAX(CASE WHEN om.class = 11 THEN term3 END) as term3,
       MAX(CASE WHEN om.class = 11 THEN final END) as final,
       MAX(CASE WHEN om.class = 12 THEN academicyear END) as academicyear,
       MAX(CASE WHEN om.class = 12 THEN class END) as class,
       MAX(CASE WHEN om.class = 12 THEN term1 END) as term1,
       MAX(CASE WHEN om.class = 12 THEN term2 END) as term2,
       MAX(CASE WHEN om.class = 12 THEN term3 END) as term3,
       MAX(CASE WHEN om.class = 12 THEN final END) as final              
FROM dbo.New_Portal_OldMarks om
GROUP BY om.ID, om.StudentID, om.[Student Name], om.SubjectName