MYSQL中多行转一行实践

  • Post author:
  • Post category:mysql


CREATE TABLE `studen` (
  `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `name` varchar(64) NOT NULL COMMENT '姓名',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COMMENT='学生表';

insert into studen values(1,'李伟');
insert into studen values(2,'李四');
insert into studen values(3,'王五');

CREATE TABLE `studen2` (
  `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `sub` varchar(64) NOT NULL COMMENT '科目',
  `score` varchar(64) NOT NULL COMMENT '分数',
   PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COMMENT='学生表2';

insert into studen2 values(1,'语文','88');
insert into studen2 values(1,'英语','100');
insert into studen2 values(3,'数学','99');

select 
a.id,a.name,
sum(case sub when'英语' then score  else 0 end) as '英语',
sum(case sub when'语文' then score  else 0 end) as '语文',
sum(case sub when'数学' then score  else 0 end )as '数学'
 from 
studen a left join studen2 b on a.id=b.id
group by a.id,a.name;



版权声明:本文为zhaomengszu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。