SQL语句中行转列案例

--初始化示例
DECLARE @StudentGrade TABLE(student NVARCHAR(20), scoure NVARCHAR(20), grade DECIMAL)

INSERT @StudentGrade(student,scoure,grade)
VALUES('张三','chinese',96)

INSERT @StudentGrade(student,scoure,grade)
VALUES('张三','maths',82)

INSERT @StudentGrade(student,scoure,grade)
VALUES('张三','english',79)

INSERT @StudentGrade(student,scoure,grade)
VALUES('李四','maths',61)

INSERT @StudentGrade(student,scoure,grade)
VALUES('李四','english',58)

INSERT @StudentGrade(student,scoure,grade)
VALUES('王五','chinese',100)

INSERT @StudentGrade(student,scoure,grade)
VALUES('王五','english',97)

--原表查询
SELECT * FROM @StudentGrade

--列转行后查询
SELECT *
FROM @StudentGrade
PIVOT(MAX(grade) FOR scoure in(chinese,maths,english))AS up
 

你可能感兴趣的:(MS-SQL,学习笔记)