首页 / MYSQL / Mysql-sql行转列
Mysql-sql行转列
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Mysql-sql行转列,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2400字,纯文字阅读大概需要4分钟。
内容图文
原始数据如下图所示:(商品的销售明细)
date=业务日期;Item=商品名称;saleqty=销售数量
-- 建立测试数据(表)
create table test (Date varchar(10), item char(10),saleqty int);
insert test values(‘2010-01-01‘,‘AAA‘,8);
insert test values(‘2010-01-02‘,‘AAA‘,4);
insert test values(‘2010-01-03‘,‘AAA‘,5);
insert test values(‘2010-01-01‘,‘BBB‘,1);
insert test values(‘2010-01-02‘,‘CCC‘,2);
insert test values(‘2010-01-03‘,‘DDD‘,6);
实现的方法和思路如下:两个方法
-- 实现结果的静态SQL语句写法
-- 整理报表需要的格式
方法一:case item when x then xx when y then yy end
select date,
case item when ‘AAA‘ then saleqty end as AAA,
case item when ‘BBB‘ then saleqty end as BBB,
case item when ‘CCC‘ then saleqty end as CCC,
case item when ‘DDD‘ then saleqty end as DDD
from test;
方法二:if(条件判断,成立结果,不成立结果)
select date,
if (item = ‘AAA‘,saleqty,null) as AAA,
if (item = ‘BBB‘,saleqty,null) as BBB,
if (item = ‘CCC‘,saleqty,null) as CCC,
if (item = ‘DDD‘,saleqty,null) as DDD
from test;
-- 按日期汇总行
select date,
sum(case item when ‘AAA‘ then saleqty end)as AAA,
sum(case item when ‘BBB‘ then saleqty end)as BBB,
sum(case item when ‘CCC‘ then saleqty end)as CCC,
sum(case item when ‘DDD‘ then saleqty end)as DDD
from test group by date;
select date,
sum(if (item = ‘AAA‘,saleqty,null)) as AAA,
sum(if (item = ‘BBB‘,saleqty,null)) as BBB,
sum(if (item = ‘CCC‘,saleqty,null)) as CCC,
sum(if (item = ‘DDD‘,saleqty,null)) as DDD
from test group by date;
-- 处理数据:将空值的栏位填入数字0;
select date,
ifnull(sum(case item when ‘AAA‘ then saleqty end) ,0)as AAA,
ifnull(sum(case item when ‘BBB‘ then saleqty end) ,0)as BBB,
ifnull(sum(case item when ‘CCC‘ then saleqty end) ,0)as CCC,
ifnull(sum(case item when ‘DDD‘ then saleqty end) ,0)as DDD
from test group by date;
select date,
ifnull(sum(if (item = ‘AAA‘,saleqty,null)),0) as AAA,
ifnull(sum(if (item = ‘BBB‘,saleqty,null)),0) as BBB,
ifnull(sum(if (item = ‘CCC‘,saleqty,null)),0) as CCC,
ifnull(sum(if (item = ‘DDD‘,saleqty,null)),0) as DDD
from test group by date;
静态SQL语句编写完成!
其实有一步骤有点多余:可以直接if(,,0),而不是if(,,null)
select date,
if (item = ‘AAA‘,saleqty,0) as AAA,
if (item = ‘BBB‘,saleqty,0) as BBB,
if (item = ‘CCC‘,saleqty,0) as CCC,
if (item = ‘DDD‘,saleqty,0) as DDD
from test;
select date,
sum(if (item = ‘AAA‘,saleqty,0)) as AAA,
sum(if (item = ‘BBB‘,saleqty,0)) as BBB,
sum(if (item = ‘CCC‘,saleqty,0)) as CCC,
sum(if (item = ‘DDD‘,saleqty,0)) as DDD
from test group by date;
静态SQL语句编写完成!
参考网址https://www.cnblogs.com/ShaYeBlog/p/3594517.html
原文:https://www.cnblogs.com/wqbin/p/10223894.html
内容总结
以上是互联网集市为您收集整理的Mysql-sql行转列全部内容,希望文章能够帮你解决Mysql-sql行转列所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。