0

桌子:

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

输出:

id  Subject1    Subject2    Subject3
1   Math        Eng 
2   Sci         Phy         bio

所需的输出如上所示。

4

2 回答 2

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

于 2018-12-14T10:51:13.117 回答
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
BRA 1 3 0 1 2
CHN 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

select * from olympic_country_sport_medals unpivot ( (medals) for sport in (ath, box, gym, sai, cyc) ) pivot ( sum(medals) for noc in ('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

于 2018-12-14T10:55:59.417 回答