将两列PIVOT分成多行

时间:2014-03-29 05:38:43

标签: sql pivot

来源表

Subject_Name   Semester
------------------------
A1               1
B1               2
C1               3
D1               1
E1               2

所需输出

1    2   3
---------------
A1  B1   C1
D1  E1

1 个答案:

答案 0 :(得分:1)

试试这个

;WITH cte 
     AS (SELECT subject_name, 
                semester, 
                Row_number() OVER (partition BY semester ORDER BY subject_name DESC) AS Rn 
         FROM   sourcetable) 
SELECT [1], 
       [2], 
       [3] 
FROM   cte 
       PIVOT (Max(subject_name) 
             FOR semester IN ([1],[2],[3])) pvt 

SELECT * 
FROM   (SELECT subject_name, 
               semester, 
               Row_number() OVER(partition BY semester ORDER BY subject_name DESC) AS Rn 
        FROM   sourcetable) src 
        PIVOT ( Max(subject_name) 
             FOR semester IN ([1],[2],[3]) ) piv 

Fiddle Demo

<强>输出

1   2    3
A1  B1   C1
D1  E1   null