SQL_行轉列

1. 背景

在某個面試中做到了行轉列的筆試題,因爲無數據測試,當時寫的也不確定,所以創建了一個用例測試了一下。數據如下圖(比較簡單),要做的是得到一個新表,列分別是ID、math_score、english_score、python_score、sql_score
在這裏插入圖片描述

2. 代碼

代碼如下圖:

select ID,
max(case subject when 'math' then score else 0 end) as math_score,
max(case subject when 'english' then score else 0 end) as english_score,
max(case subject when 'python' then score else 0 end) as python_score,
max(case subject when 'sql' then score else 0 end) as sql_score
from sc
group by ID

SELECT * FROM sc pivot ( max( score ) FOR sub IN ([math],[english],[python],[sql]) 
) AS a

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章