不管我们在平时的学习或工作中,难免会遇到“行转列”与“列转行“”的数据操作,我们先看一下今天我们需要实现的例子
1、我们的数据是这样的
2、我们需要输出的数据是这样的
可以先自己思考一下如何实现
----------------------------------- ^_^ 这是思考线 ^_^ -------------------------------------------
1、先创建表
drop table if exists dina_test_table ; create table dina_test_table(date varchar(10),order_cnt int,payment double,goods_cnt int);2、插入测试数据
insert into dina_test_table values('2020-01',90,3357.89,100); insert into dina_test_table values('2020-02',20,659.75,22); insert into dina_test_table values('2020-03',27,636.52,30); insert into dina_test_table values('2020-04',30,869.09,46); insert into dina_test_table values('2020-05',56,2834.57,70); insert into dina_test_table values('2020-06',85,3924.35,99);3、看一下测试数据
4、实现的代码(仅供参考)
-- 先将测试数据列转行 再将中间结果 行转列,就可以了 select -- 将数据行专列 object, max(case when date='2020-01' then value else null end)`2020-01`, max(case when date='2020-02' then value else null end)`2020-02`, max(case when date='2020-03' then value else null end)`2020-03`, max(case when date='2020-04' then value else null end)`2020-04`, max(case when date='2020-05' then value else null end)`2020-05`, max(case when date='2020-06' then value else null end)`2020-06` from( -- 将数据列转行 select date,'订单数' as object, order_cnt as value from dina_test_table union all select date,'销售额' as object, payment as value from dina_test_table union all select date,'商品销售数量' as object, goods_cnt as value from dina_test_table )t group by object order by (case when object = '订单数' then 1 when object = '销售额' then 2 when object = '商品数量' then 3 end)5、执行SQL 即可得到以下的效果
希望对你有帮助!!!
若想了解 MySQL 的 行转列 实现小示例,可点击 此处
若想了解 MySQL 的 列转行 实现小示例,可点击 此处