您的位置:首页 > 博客中心 > 数据库 >

sql实现行列转换

时间:2022-03-14 01:38


姓名 科目 成绩
牛芬 语文 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

就这么简单

热门排行

今日推荐

热门手游