sql實現行列轉換


姓名 科目 成績
牛芬 語文 81
牛芬 數學 88
牛芬 英語 84
張三 語文 90
張三 數學 98
張三 英語 90

(表一)

現有一個表如(表一)

姓名 語文 數學 英語
牛芬 81 88 84
張三 90 98 90
(表二)

想要轉換爲(表二)

sql:select  stuName as 姓名,chinese as 語文,math as 數學,english as 英文 from(

select sutName,

case subject when chinese then score end as chinese,

case subject when math then score end as math,

case subject when english then score end as english

from table) as tmp

group by stuName


若要把(表二)轉換成(表一)

postgresql裏面有個unnest函數可以使用:

select stuName,unnest(array['chinese','math','english']) as subject,unnest(array[chinest,math,englist]) as score from table group by stuName

就這麼簡單

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