天天看點

sql 列轉行_SQL面試題:如何行列互換?一個萬能模闆

sql 列轉行_SQL面試題:如何行列互換?一個萬能模闆

三個步驟:

  1. 輸出行列互換的結構表
  2. 再用case...when...來輸出資料
  3. 用group by及max輸出最終結果
1。輸出行列互換的結構表
SELECT 學号,'課程編号0001','課程編号0002','課程編号0003' from score;           
sql 列轉行_SQL面試題:如何行列互換?一個萬能模闆
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;           
sql 列轉行_SQL面試題:如何行列互換?一個萬能模闆
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 學号;           
sql 列轉行_SQL面試題:如何行列互換?一個萬能模闆
拓展,列轉行
sql 列轉行_SQL面試題:如何行列互換?一個萬能模闆
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面試題:行列如何互換?

繼續閱讀