最近准备面试题,想之前面试过一家公司时遇到一个sql题,横向展示一个表中数据,当时没写出现写下总结,以免忘记。
-- ------------------------------ table structure for `t_subject`-- ----------------------------drop table if exists `t_subject`;create table `t_subject` ( `id` int(11) not null default '0', `name` varchar(255) default null, `subject` varchar(255) default null, `results` int(11) default null, primary key (`id`)) engine=innodb default charset=utf8;-- ------------------------------ records of t_subject-- ----------------------------insert into `t_subject` values ('1', '小明', '语文', '50');insert into `t_subject` values ('2', '小明', '数学', '20');insert into `t_subject` values ('3', '小乐', '英语', '122');insert into `t_subject` values ('4', '小乐', '语文', '500');insert into `t_subject` values ('5', '小二', '数学', '100');
有一张表,表中包含一个三个人有三个科目。
select t.name , sum( if ( t.subject = '语文', t.results, 0 ) ) as '语文', sum( if ( t.subject = '数学', t.results, 0 ) ) as '数学', sum( if ( t.subject = '英语', t.results, 0 ) ) as '英语'from t_subject tgroup by (t.name);
执行结果如下:
当时很好奇为什么需要加sum函数进行求和,去掉之后执行sql如下
初步分析如果不加此函数sql执行默认只会对进行分组后的数据进行统计
select *from t_subject tgroup by t.name;