桌子:
ID Subject
1 Math
1 Eng
2 Sci
2 Phy
2 bio
输出:
id Subject1 Subject2 Subject3
1 Math Eng
2 Sci Phy bio
所需的输出如上所示。
我会使用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
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