mysql中sql行转列_Mysql-sql行转列

原始数据如下图所示:(商品的销售明细)

date=业务日期;Item=商品名称;saleqty=销售数量

bc4d3648e1f99c40a4f7b2550f13eb16.png

-- 建立测试数据(表)

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;

1b0b9a4d31404c6e214faebcce9fb316.png

-- 按日期汇总行

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;

9b43a4a77a3b7b189352ee31d6d677e5.png

-- 处理数据:将空值的栏位填入数字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;

53bf3a31f18215ecb4ec05ab0ad7269f.png

静态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;

322873131b43181c46e469f72cf431f5.png

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;

069cd401a00f26e63ac30b7bea687e23.png

静态SQL语句编写完成!

参考网址https://www.cnblogs.com/ShaYeBlog/p/3594517.html

原文:https://www.cnblogs.com/wqbin/p/10223894.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值