1. 程式人生 > >動態獲取列名,行列轉置

動態獲取列名,行列轉置

USE tempdb
GO
IF OBJECT_ID('Student') IS NOT NULL DROP TABLE Student
IF OBJECT_ID('Course') IS NOT NULL DROP TABLE Course
IF OBJECT_ID('Scores') IS NOT NULL DROP TABLE Scores
GO
CREATE TABLE Student(StudentID INT PRIMARY KEY,StudentName NVARCHAR(10))
CREATE TABLE Course(CourseID INT,CourseName NVARCHAR(10))
CREATE TABLE Scores(CourseID INT,StudentID INT,score INT)
GO
SET NOCOUNT ON
INSERT INTO Student
SELECT  1,N'張'
union ALL SELECT 2,N'李'

INSERT INTO Course
SELECT 1,N'語文'
union ALL SELECT 2,N'數學'
union ALL SELECT 3,N'英語'

INSERT INTO Scores
SELECT 1,1,78
union ALL SELECT 2,1,79
union ALL SELECT 3,1,80
union ALL SELECT 1,2,81
union ALL SELECT 2,2,82
union ALL SELECT 3,2,83

--靜態
SELECT 
StudentName  AS [姓名]
,MAX(CASE WHEN c.CourseName=N'語文' THEN s.score ELSE 0 END) AS [語文]
,MAX(CASE WHEN c.CourseName=N'數學' THEN s.score ELSE 0 END) AS [數學]
,MAX(CASE WHEN c.CourseName=N'英語' THEN s.score ELSE 0 END) AS [英語]
FROM Student AS stu LEFT JOIN Scores AS s ON stu.StudentID=s.StudentID 
	LEFT JOIN Course AS c ON s.CourseID=c.CourseID
GROUP BY stu.StudentName,stu.StudentID

動態:

------------ 動態獲取列名, 行列轉置 ---------------
DECLARE @sql NVARCHAR(MAX)
SET @sql='
SELECT 
StudentName  AS [姓名]
'+
(
SELECT 
',MAX(CASE WHEN c.CourseName=N'''+c.CourseName+''' THEN s.score ELSE 0 END) AS ['+c.CourseName+']'
FROM dbo.Course AS c
FOR XML PATH('')
)
+
'FROM Student AS stu LEFT JOIN Scores AS s ON stu.StudentID=s.StudentID 
	LEFT JOIN Course AS c ON s.CourseID=c.CourseID
GROUP BY stu.StudentName,stu.StudentID'
PRINT @sql
EXEC (@sql)