首页 > 数据库技术 > 详细

SQL 实现行列互换

时间:2016-02-22 12:09:52      阅读:194      评论:0      收藏:0      [点我收藏+]

Oracle:不过大多数是采用 oracle 数据库当中的一些便捷函数进行处理,比如 ”pivot”;

MySql:目前没有找到更好的方法

题目:数据库中有一张如下所示的表,表名为sales。

季度销售量
1991 1 11
1991 2 12
1991 3 13
1991 4 14
1992 1 21
1992 2 22
1992 3 23
1992 4 24


要求:写一个SQL语句查询出如下所示的结果。

一季度二季度三季度四季度
1991 11 12 13 14
1992 21 22 23 24


我给出的答案是这样的:

1 select 年, 
2 sum(case when 季度=1 then 销售量 else 0 end) as 一季度, 
3 sum(case when 季度=2 then 销售量 else 0 end) as 二季度, 
4 sum(case when 季度=3 then 销售量 else 0 end) as 三季度, 
5 sum(case when 季度=4 then 销售量 else 0 end) as 四季度 
6 from sales group by 年;

 

SQL 实现行列互换

原文:http://www.cnblogs.com/QQ931697811/p/5206546.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!