SQL語句中行轉列案例
阿新 • • 發佈:2019-02-20
案例一:
CREATE TABLE #t(Id INT,TypeVal VARCHAR(10),ValueVal VARCHAR(20));
INSERT INTO #t (Id,TypeVal,ValueVal)VALUES (1,'a','ValA'),(1,'a','ValB'),(2,'b','ValC'),(1,'c','ValD'),(2,'c','ValD'),(2,'a','ValD'),(3,'c','ValD')
SELECT * FROM #t
SELECT id,a,b,c
FROM (
SELECT t.Id,t.TypeVal,MAX(o.ValueVals) AS ValueVals
FROM #t AS t WITH(NOLOCK)
CROSS APPLY(
SELECT STUFF((SELECT ','+t2.ValueVal
FROM #t AS t2 WITH(NOLOCK)
WHERE t.Id=t2.Id AND t.TypeVal=t2.TypeVal
FOR XML PATH('')),1,1,'') AS ValueVals
) AS o
GROUP BY t.Id,t.TypeVal
) AS ts
PIVOT(
max(ts.ValueVals) FOR ts.TypeVal IN (a,b,c)
) AS p
DROP TABLE #t
案例二:
/*******************************************************************************
*課程表:Course
********************************************************************************/
CREATE TABLE #Course(CourseName VARCHAR(10));
INSERT INTO #Course (CourseName)
VALUES ('語文'),('數學'),('英語')
SELECT * FROM #Course
/*******************************************************************************
*學生成績表:Score
********************************************************************************/
CREATE TABLE #Score(StudentName VARCHAR(10),CourseName VARCHAR(10),Score INT);
INSERT INTO #Score (StudentName,CourseName,Score)
VALUES ('小紅','語文',76),('小紅','數學',85),('小紅','英語',55),
('小李','語文',90),('小李','數學',69),('小李','英語',74),
('小林','語文',87),('小林','數學',90),('小林','英語',88)
SELECT * FROM #Score
/*******************************************************************************
*組織所有的課程
********************************************************************************/
DECLARE @CourseName VARCHAR(200) = ''
DECLARE @SelectSQL NVARCHAR(2000)
SELECT @CourseName = @CourseName + '[' + CourseName + '],'
FROM #Course
SET @CourseName = LEFT(@CourseName, LEN(@CourseName) - 1)
/*******************************************************************************
*行轉列操作
********************************************************************************/
SET @SelectSQL = 'SELECT pvt.*
FROM
(
SELECT StudentName, CourseName, Score FROM #Score
) p
PIVOT( SUM(Score) For CourseName in ({0})) AS pvt'
SET @SelectSQL = REPLACE(@SelectSQL, '{0}', @CourseName)
EXEC sp_executesql @SelectSQL
/*******************************************************************************
*刪除臨時表
********************************************************************************/
DROP TABLE #Course
DROP TABLE #Score