sql 行列转换

建表语句

/*Table structure for table `score` */

drop table if exists `score`;

CREATE TABLE `score` (
`id` int(10) NOT NULL auto_increment,
`score` int(3) default NULL,
`subject` int(10) default NULL,
`student` int(10) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

/*Data for the table `score` */

insert into `score` values (1,100,1,1),(2,99,2,1),(3,99,1,2),(4,98,2,2),(5,99,3,2);

/*Table structure for table `student` */

drop table if exists `student`;

CREATE TABLE `student` (
`id` int(10) NOT NULL auto_increment,
`name` varchar(20) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

/*Data for the table `student` */

insert into `student` values (1,'zhangsan'),(2,'lisi');

/*Table structure for table `subject` */

drop table if exists `subject`;

CREATE TABLE `subject` (
`id` int(10) NOT NULL auto_increment,
`subject` varchar(20) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

/*Data for the table `subject` */

insert into `subject` values (1,'chinese'),(2,'math'),(3,'english');




查询语句

select t.* ,(t.chinese + t.math+ t.english) as total from (select stu.name,max(case sub.subject when 'chinese' then s.score else 0 end) as chinese,max(case sub.subject when 'math' then s.score else 0 end) as math,max(case sub.subject when 'english' then s.score else 0 end) as english from student stu,score s,subject sub where stu.id = s.student and sub.id = s.subject group by name) t


结果:
[img]http://dl.iteye.com/upload/attachment/0067/8315/b68712ca-a75f-371e-8bb0-a46829f5d94d.png[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值