sql语句将行列进行转换
2015-06-11 17:53
477 查看
今天学习了一下如何将一张表中的某列数据由多行改成多列的写法。
如下面:pay_charge表中(为方便假设只有二列wg_user_no户号,price单价)
同一个户号wg_user_no 在表中可能存在二行不同的price值,如
wg_user_no price
10111011 1.58
10111011 2.37
现在要将它变为:
wg_user_no price1 price2
10111011 1.58 2.37
代码如下:
1
如下面:pay_charge表中(为方便假设只有二列wg_user_no户号,price单价)
同一个户号wg_user_no 在表中可能存在二行不同的price值,如
wg_user_no price
10111011 1.58
10111011 2.37
现在要将它变为:
wg_user_no price1 price2
10111011 1.58 2.37
代码如下:
--原始表 select wg_user_no,price from pay_charge --第1步 创建伪列 select wg_user_no, case when price= '1.58' then price else '0' end L1, case when price= '2.37' then price else '0' end L2 from ( select wg_user_no,price from pay_charge where length(wg_user_no)=10 and price in('1.58','2.37') order by wg_user_no ) order by wg_user_no --第2步 分组求和 select wg_user_no,sum(L1) l1,sum(L2) l2 from ( select wg_user_no, case when price= '1.58' then price else '0' end L1, case when price= '2.37' then price else '0' end L2 from ( select wg_user_no,price from pay_charge where length(wg_user_no)=10 and price in('1.58','2.37') order by wg_user_no ) ) group by wg_user_no having sum(L2)>0 ; --改case为decode函数 select wg_user_no,sum(L1) l1,sum(L2) l2 from ( select wg_user_no, decode(price,'1.58',price,'0') L1, decode(price,'2.37',price,'0') L2 from ( select wg_user_no,price from pay_charge where length(wg_user_no)=10 and price in('1.58','2.37') order by wg_user_no ) ) group by wg_user_no having sum(L2)>0
1
相关文章推荐
- 如何查看mysql的隔离级别
- 【SQL】DBCC
- ORCLE 性能调优概述
- Redis介绍以及安装(Linux)
- Oracle数据库入门——体系结构
- .net连接oracle数据库---Shinepans
- Redis过期键删除策略
- mysql分区功能详细介绍,以及实例
- 灾备用Oracle语句备查
- SQL重置自增列
- mysql性能优化-慢查询分析、优化索引和配置
- MySQL查询优化程序
- mysql主从:主键冲突问题
- mongodb预先分配数据文件
- mysql 5.5主从复制配置
- 数据库复习2——SQL基础
- MYSQL随机抽取查询 MySQL Order By Rand()效率问题
- mybatis中关于sqlMapConfig配置
- 在mysql的命令行中设置字符集
- 浅析数据库连接池(二)