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

就这么简单

版权声明:本文博主原创文章,博客,未经同意不得转载。

posted @ 2015-10-13 14:23  hrhguanli  阅读(165)  评论(0编辑  收藏  举报