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