SQL Server pivot指定列

时间:2014-04-28 10:48:23

标签: sql-server sql-server-2012

我正在努力解决查询输出问题。请参阅示例数据:

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

对于成绩输出,我想将成绩栏中的一些重要成绩类型设置为他们的OWN列。即Current,Final我希望将其创建为具有相关等级的自己的列,但其他列可以被列出,因为它们并不重要。这是一个非常简单的例子,我使用的数据要复杂得多。

他们是否可以指定要创建的重要列作为自己的列和其他数据按照正常情况列出?此外,我见过的所有数据透视示例都是从一个表中查询。如果您的查询有多个连接,会发生什么?

1 个答案:

答案 0 :(得分:1)

你的目标是这样:

;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