码迷,mamicode.com
首页 > 数据库 > 详细

SQL语句的行列转换

时间:2016-02-18 22:43:40      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

【一】行转列

1,查询原始的数据

/***这次练习的主题,行转列,列转行***/
select * from Scores

技术分享

2,得到姓名,通过group by

select Student as ‘姓名‘
from Scores
group by Student
order by Student

技术分享

3,再加上max, case……when

技术分享
select Student as ‘姓名‘,
max(case Subject when ‘语文‘ then Score else 0 end) as ‘语文‘ ,--如果这个行是“语文”,就选此行作为列
max(case Subject when ‘英语‘ then Score else 0 end ) as ‘英语‘
from Scores
group by Student
order by Student
技术分享

技术分享

 

查看其它资料时,看到另外一种方法,用pivot

技术分享
--group by, avg/max, pivot。这里用max和avg,结果都一样,有什么区别吗?有点不明白
--参考网上的资料,用法如下
/*
pivot(
  聚合函数(要转成列值的列名)
  for 要转换的列
  in(目标列名)
  )
*/
select Student as ‘姓名‘,
avg(语文) as ‘语文‘,
avg(英语) as ‘英语‘
from Scores
pivot(
avg(Score) for Subject
in (语文,英语)
)as NewScores
group by Student
order by Student asc
技术分享

SQL语句的行列转换

标签:

原文地址:http://www.cnblogs.com/ziyandeyanhuo/p/5199390.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!