SQL组合多个表和透视

时间:2014-05-13 04:02:27

标签: sql sql-server tsql

我有这些表

Student - studentID, batchID, courseID, FirstName, Last Name ...
Subject - subjectID, courseID, subjectName ...
Mark - markID, studentID, subjectID, Marks
Course - courseID, courseName ...

我已经尝试了这么久,终于结束了......

SELECT S.studentID AS 'ID', S.FirstName + ' ' + S.LastName AS 'Full Name', M.Marks AS 'Subject'
FROM Student AS S
LEFT JOIN Mark AS M ON S.studentID = M.studentID AND M.subjectID = 'S1001'
WHERE S.batchID = 1

这个只显示一个主题的数据,主题名称由C#(Winforms)使用subjectID生成。

Student ID | Full Name    | Elementary Programming in C
-------------------------------------------------------
    1      | student name |        50
    2      | abc          |        80

但是我希望它显示该课程中的所有主题以及该列中的相应标记,如下所示(如果我必须使用Winforms生成列标题,如果给出subjectID)...

Student ID | Full Name    | Elementary Programming in C | HTML | ...
-----------------------------------------------------------------
    1      | student name |        50                   |  70  | ...
    2      | abc          |        80                   |  60  | ...

我尝试过使用枢轴,但不是很成功...... 希望有人可以给我一两个想法,如果你需要更多信息,请问......

1 个答案:

答案 0 :(得分:0)

试试这个,     DECLARE @cols AS NVARCHAR(MAX),         @query AS NVARCHAR(MAX)

select @cols = stuff((select distinct ',' + quotename(subjectName) 
                from Subject WHERE courseID = 'C1001'
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

set @query = 'select studentID,' + @cols + '
         from 
         (
            select S.studentID, ss.subjectID, M.Marks
            from Student S
              join Subject ss on S.courseID = ss.courseID 
              join Mark M on M.subjectID = ss.SubjectID AND M.studentID = S.StudentID
            where S.batchID = 1
        ) x
        pivot 
        (
            max(Marks)
            for subjectName in (' + @cols + ')
        ) p '

execute(@query)