Question

I'm struggling with a query output issue. Please see sample data :

CREATE TABLE #Subject (ID INT PRIMARY KEY IDENTITY, Name NVARCHAR(50))
CREATE TABLE #Student (ID INT PRIMARY KEY IDENTITY, Name NVARCHAR(50))
CREATE TABLE #Grade (ID INT PRIMARY KEY IDENTITY,
       StudentID INT REFERENCES #Student(ID),
       SubjectID INT REFERENCES #Subject(ID),
       Grade NVARCHAR(50), GradeText NVARCHAR(50))

INSERT INTO #Subject ( Name ) VALUES
(N'Maths'),
(N'Physics'),
(N'English')

INSERT INTO #Student ( Name ) VALUES
(N'Joe'),
(N'Tom'),
(N'Sally'),
(N'Fred'),
(N'Kim')

INSERT INTO #Grade
    (  StudentID, SubjectID, Grade, GradeText ) VALUES
(1,1,'Current','A'),
(2,3,'Expected','C'),
(3,2,'Mid','F'),
(4,1,'Final','B'),
(5,2,'Pre','C'),
(2,3,'Start','A'),
(3,1,'Current','A'),
( 1,2,'Expected','B'),
( 4,1,'Final','D'),
( 5,3,'Mid','E')

SELECT * FROM #Student
SELECT * FROM #Subject
SELECT * FROM #Grade

For the grade output I want to set some of the important grade types in the grade column to be their OWN columns. i.e. Current, Final I would like to be created as their own columns with associated grades, but the others can just be listed as they're not as important. This is a very simple example, the data I'm working with is much more complicated.

Is their a way to specify important columns to be created as their own columns and other data to just be listed as per normal? Also, all the pivot examples I've seen are querying from one table. What happens when you're query has many joins?

Was it helpful?

Solution

Are you aiming at something like this:

;with x as (
    select *
    from (
        select StudentID, SubjectID, Grade, GradeText, Grade as grade_1, GradeText as GradeText_1
            from (
            select *
            from #Grade 
        ) as x
    ) as source
    pivot (
        max(GradeText_1)
        for Grade_1 in ([Current], [Final])
    ) as pvt
)
select sub.Name as Subject, st.Name as Student, Grade, GradeText, [Current], Final
from x
inner join #Subject sub on x.SubjectID = sub.ID
inner join #Student st on x.StudentID = st.ID
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top