mysql 行专列
2015-09-07 14:28
906 查看
以备后用查找
CREATE TABLE student (
id INT NOT NULL auto_increment,
`name` varchar(50) DEFAULT NULL,
`subject` varchar(50) DEFAULT NULL,
`score` int(11) DEFAULT NULL,
primary key (id)
);
insert into student(name,subject,score) values
('刘能' , 'chinese' , 10),
('刘能' , 'math' , 20),
('刘能' , 'english' , 30),
('赵四' , 'chinese' , 40),
('赵四' , 'math' , 50),
('赵四' , 'english' , 60),
('谢广坤' , 'chinese' , 70),
('谢广坤' , 'math' , 80),
('谢广坤' , 'english' , 90);
第1种方式: case when
select name,
sum( case subject when 'chinese' then score else 0 end) as 'chinese',
sum( case subject when 'math' then score else 0 end) as 'math',
sum( case subject when 'english' then score else 0 end) as 'english'
from student
group by name;
第2种方式: if( , , )
select name,
max(IF(subject = 'chinese',score,0)) as 'chinese',
max(IF(subject = 'math',score,0)) as 'math',
max(IF(subject = 'english',score,0)) as 'english',
sum(score) as'total'
from student
group by name
注: 上面的两种方式中的 max() 或 sum() 两者针对这种场景均可互换, if(, ,)感觉更简洁。两者性能没有比较过。
CREATE TABLE student (
id INT NOT NULL auto_increment,
`name` varchar(50) DEFAULT NULL,
`subject` varchar(50) DEFAULT NULL,
`score` int(11) DEFAULT NULL,
primary key (id)
);
insert into student(name,subject,score) values
('刘能' , 'chinese' , 10),
('刘能' , 'math' , 20),
('刘能' , 'english' , 30),
('赵四' , 'chinese' , 40),
('赵四' , 'math' , 50),
('赵四' , 'english' , 60),
('谢广坤' , 'chinese' , 70),
('谢广坤' , 'math' , 80),
('谢广坤' , 'english' , 90);
第1种方式: case when
select name,
sum( case subject when 'chinese' then score else 0 end) as 'chinese',
sum( case subject when 'math' then score else 0 end) as 'math',
sum( case subject when 'english' then score else 0 end) as 'english'
from student
group by name;
第2种方式: if( , , )
select name,
max(IF(subject = 'chinese',score,0)) as 'chinese',
max(IF(subject = 'math',score,0)) as 'math',
max(IF(subject = 'english',score,0)) as 'english',
sum(score) as'total'
from student
group by name
注: 上面的两种方式中的 max() 或 sum() 两者针对这种场景均可互换, if(, ,)感觉更简洁。两者性能没有比较过。
相关文章推荐
- MySQL中的integer 数据类型
- MySQL存储过程
- mysql中int、bigint、smallint 和 tinyint的区别与长度
- mysql load data 导出、导入 csv
- source命令执行SQL脚本文件
- MySQL创建用户及权限控制
- MySQL管理数据表
- linux下mysql添加用户
- mysql procedure
- mysql触发器
- MySQL 备份和恢复策略
- mac下安装mysql(转载)
- mysql 修改编码 Linux/Mac/Unix/通用(杜绝修改后无法启动的情况!)
- MySQL数据的导出、导入(mysql内部命令:mysqldump、mysql)
- mysql数据行转列
- Linux下修改MySQL编码的方法
- MySQL Server 日志
- MySQL 安全事宜