将行移到列

时间:2018-12-14 10:45:31

标签: sql oracle oracle11g pivot

表格:

ID  Subject
1   Math
1   Eng
2   Sci
2   Phy
2   bio

输出:

id  Subject1    Subject2    Subject3
1   Math        Eng 
2   Sci         Phy         bio

所需的输出如上所示。

2 个答案:

答案 0 :(得分:1)

我将使用ROW_NUMBER窗口函数和条件聚合函数

SELECT ID,
      MAX(CASE WHEN rn = 1 THEN SUBJECT END) Subject1,
      MAX(CASE WHEN rn = 2 THEN SUBJECT END) Subject2,
      MAX(CASE WHEN rn = 3 THEN SUBJECT END) Subject3    
FROM(
    SELECT t1.*,ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ROWNUM) rn
    FROM T t1
) t1 
GROUP BY ID

https://rextester.com/TMGK34943

答案 1 :(得分:0)

https://blogs.oracle.com/sql/how-to-convert-rows-to-columns-and-back-again-with-sql-aka-pivot-and-unpivot#transpose

NOC ATH GYM CYC BOX SAI
胸罩1 3 0 1 2
中国6 2 2 4 1
DEN 1 0 2 0 3
ESP 2 0 0 0 0
ETH 8 0 0 0 0
GRE 1 1 0 0 2

从“奥运国家/体育奖牌”中选择* 取消枢纽(   运动(奖牌)在(Ath,Box,Gym,sai,cyc) ) 枢轴(   ()中noc的总和(奖牌)     'BRA'BRA,'CHN'CHN,'DEN'DEN,'ESP'ESP,'ETH'ETH,'GRE'GRE   ) );

输出:

SPORT BRA CHN DEN ESP ETH GRE
田径运动1 6 1 2 8 1
艺术馆3 2 0 0 0 1
拳击1 4 0 0 0 0
帆船2 1 3 0 0 2
跟踪单车0 2 2 0 0 0