Question

I have these tables

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

I have been trying this for so long and finally ended up with this...

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

This one only shows the data for only one subject and the subject name is being generated by C# (Winforms) using the subjectID.

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

but I want it to show all the subjects in that course and the respective marks in that column, like this (don't mind if i have to generate column headers using Winforms if subjectID is given)...

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

I have tried using pivot, but it wasn't very successful... Hope someone can give me an idea or two, and if you need more information just ask...

Was it helpful?

Solution

Try this, 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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top