创建测试表:
drop table if exists `test`;
create table `test` (
`year` int(11) default null,
`month` int(11) default null,
`amount` double default null
) engine=innodb default charset=utf8;
插入数据:
insert into `test` values ('1991', '1', '1.1');
insert into `test` values ('1991', '2', '1.2');
insert into `test` values ('1991', '3', '1.3');
insert into `test` values ('1991', '4', '1.4');
insert into `test` values ('1992', '1', '2.1');
insert into `test` values ('1992', '2', '2.2');
insert into `test` values ('1992', '3', '2.3');
insert into `test` values ('1992', '4', '2.3');
看到题目要求,仔细想想可以:
利用sum(if()) 生成列 + with rollup 生成汇总行,并利用 ifnull将汇总行标题显示为 total_num
实现
sql代码块如下:
select year,
sum(if(month=1,amount,0)) as "m1",
sum(if(month=2,amount,0)) as "m2",
sum(if(month=3,amount,0)) as "m3",
sum(if(month=4,amount,0)) as "m4"
from test
group by year;
效果如下:
以上所述是小编给大家介绍的mysql的列修改成行并显示数据的简单实现,希望对大家有所帮助
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!