数据库表的转换

创建三张表

create table student(
    id varchar(10),
    name varchar(10)
);
desc student;

create table subject(
    subid varchar(10),
	subname varchar(10)
);
desc subject;

create table score(
    scoreid int,
	subid  varchar(10),
	stdid varchar(10),
	score  int(3)
);

desc score9;

插入数据

insert into student values ('a001','张三'),('a002','王强');

insert into subject values ('s001','英语'),('s002','数学'),('s003','语文'),('s004','历史');

insert into score values (1,'s001','a001',78),(2,'s002','a001',67),(3,'s003','a001',89),(4,'s004','a001',89),													(5,'s001','a002',89),(6,'s002','a002',67),(7,'s003','a002',84),(8,'s004','a002',96);

查询表中数据

select * from student;
select * from subject;
select * from score;

先将三张表连接成一张表结构

select student.name,subject.subname,scoreid,score 
		from student join score on student.id = score.stdid 
					 join subject on subject.subid = score.subid;

在这里插入图片描述
将横表转化为纵表

select s.name '姓名',
	sum(case s.subname when '语文' then s.score else 0 end) '语文',
	sum(case s.subname when '数学' then s.score else 0 end) '数学',
	sum(case s.subname when '英语' then s.score else 0 end) '英语',
	sum(case s.subname when '历史' then s.score else 0 end) '历史'
from (select student.name,subject.subname,scoreid,score 
		from student join score on student.id = score.stdid 
					 join subject on subject.subid = score.subid) s
group by s.name;

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值