mysql 单列转换为行,mysql行转换为列

1.建表

CREATE TABLE `t_log_code_num` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`server_id` int(3) NOT NULL,

`date` date NOT NULL,

`code` varchar(20) NOT NULL,

`num` int(10) NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=MyISAM DEFAULT CHARSET=utf8;

2.录入数据

INSERT INTO t_log_code_num (`server_id`, `date`, `code`, `num`) VALUES (‘1‘, ‘2017-07-31‘, ‘201058‘, ‘1‘);

INSERT INTO t_log_code_num (`server_id`, `date`, `code`, `num`) VALUES (‘2‘, ‘2017-07-31‘, ‘201612‘, ‘2113‘);

INSERT INTO t_log_code_num (`server_id`, `date`, `code`, `num`) VALUES (‘1‘, ‘2017-07-30‘, ‘201058‘, ‘1‘);

INSERT INTO t_log_code_num (`server_id`, `date`, `code`, `num`) VALUES (‘2‘, ‘2017-07-30‘, ‘201314‘, ‘310‘);

INSERT INTO t_log_code_num (`server_id`, `date`, `code`, `num`) VALUES (‘1‘, ‘2017-07-29‘, ‘201322‘, ‘1890‘);

INSERT INTO t_log_code_num (`server_id`, `date`, `code`, `num`) VALUES (‘2‘, ‘2017-07-29‘, ‘201203‘, ‘379‘);

3.数据显示

20180111000409210088.png

4.统计sql

select t.`code`,

sum(case t.date when ‘2017-07-29‘ then t.num else 0 end ) as ‘2017-07-29‘,

sum(case t.date when ‘2017-07-30‘ then t.num else 0 end ) as ‘2017-07-30‘,

sum(case t.date when ‘2017-07-31‘ then t.num else 0 end ) as ‘2017-07-31‘

from (

select date,code, sum(num) num from t_log_code_num GROUP BY date,code

) t GROUP BY t.`code`;

5.统计结果

20180111000409220831.png

代码如下:

CREATE TABLE`t_log_code_num` (

`id`int(11) NOT NULLAUTO_INCREMENT,

`server_id`int(3) NOT NULL,

`date` dateNOT NULL,

`code`varchar(20) NOT NULL,

`num`int(10) NOT NULL,PRIMARY KEY(`id`)

) ENGINE=MyISAM DEFAULT CHARSET=utf8;INSERT INTO t_log_code_num (`server_id`, `date`, `code`, `num`) VALUES (‘1‘, ‘2017-07-31‘, ‘201058‘, ‘1‘);INSERT INTO t_log_code_num (`server_id`, `date`, `code`, `num`) VALUES (‘2‘, ‘2017-07-31‘, ‘201612‘, ‘2113‘);INSERT INTO t_log_code_num (`server_id`, `date`, `code`, `num`) VALUES (‘1‘, ‘2017-07-30‘, ‘201058‘, ‘1‘);INSERT INTO t_log_code_num (`server_id`, `date`, `code`, `num`) VALUES (‘2‘, ‘2017-07-30‘, ‘201314‘, ‘310‘);INSERT INTO t_log_code_num (`server_id`, `date`, `code`, `num`) VALUES (‘1‘, ‘2017-07-29‘, ‘201322‘, ‘1890‘);INSERT INTO t_log_code_num (`server_id`, `date`, `code`, `num`) VALUES (‘2‘, ‘2017-07-29‘, ‘201203‘, ‘379‘);SELECT * fromt_log_code_num;selectt.`code`,sum(case t.date when ‘2017-07-29‘ then t.num else 0 end ) as ‘2017-07-29‘,sum(case t.date when ‘2017-07-30‘ then t.num else 0 end ) as ‘2017-07-30‘,sum(case t.date when ‘2017-07-31‘ then t.num else 0 end ) as ‘2017-07-31‘

from(select date,code, sum(num) num from t_log_code_num GROUP BYdate,code

) tGROUP BY t.`code`;

原文:http://www.cnblogs.com/zhouj/p/7269930.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值