三個步驟:
- 輸出行列互換的結構表
- 再用case...when...來輸出資料
- 用group by及max輸出最終結果
SELECT 學号,'課程編号0001','課程編号0002','課程編号0003' from score;
2。再用case...when...來輸出資料 SELECT 學号,
(case when 課程号='0001' then 成績 else 0 end) as '課程号0001',
(case when 課程号='0002' then 成績 else 0 end) as '課程号0002',
(case when 課程号='0003' then 成績 else 0 end) as '課程号0003'
from score;
3.用group by及max輸出最終結果 SELECT 學号,
max(case when 課程号='0001' then 成績 else 0 end) as '課程号0001',
max(case when 課程号='0002' then 成績 else 0 end) as '課程号0002',
max(case when 課程号='0003' then 成績 else 0 end) as '課程号0003'
from score
group by 學号;
拓展,列轉行 SELECT name,'english' as subject, english as score from a1
UNION ALL
SELECT name,'maths' as subject,maths as score from a1
UNION ALL
SELECT name,'music' as subject,music as score from a1;
參考:
行列互換問題,怎麼辦?送你一個萬能模版
sql面試題:行列如何互換?
。