首先建表,主要有四个表,学生表(Student),课程表(Course),教师表(Teacher),以及成绩表(SC)
在分别介绍一下每个表的字段 学生表(Student )有四个字段 sid–学生id,sname–学生姓名,sage–学生年龄,ssex–学生性别
课程表(Course)有三个字段,cid–课程id,cname–课程名,tid–教师id
教师表(Teacher)有两个字段,tid–教师id,tname–教师姓名
成绩表(SC)有三个字段,sid–学生id,cid–课程id,score–成绩
教师表结构
成绩表结构
各个表之间的关系如下:
Student和SC表通过学生id(sid)来连接,Course和Teacher表通过教师id(tid)连接,SC和Course表通过课程id(cid)来连接。
准备数据:
create table Student(sid varchar(10),sname varchar(10),sage datetime,ssex nvarchar(10));
insert into Student values('01' , '赵雷' , '1990-01-01' , '男');
insert into Student values('02' , '钱电' , '1990-12-21' , '男');
insert into Student values('03' , '孙风' , '1990-05-20' , '男');
insert into Student values('04' , '李云' , '1990-08-06' , '男');
insert into Student values('05' , '周梅' , '1991-12-01' , '女');
insert into Student values('06' , '吴兰' , '1992-03-01' , '女');
insert into Student values('07' , '郑竹' , '1989-07-01' , '女');
insert into Student values('08' , '王菊' , '1990-01-20' , '女');
create table Course(cid varchar(10),cname varchar(10),tid varchar(10));
insert into Course values('01' , '语文' , '02');
insert into Course values('02' , '数学' , '01');
insert into Course values('03' , '英语' , '03');
create table Teacher(tid varchar(10),tname varchar(10));
insert into Teacher values('01' , '张三');
insert into Teacher values('02' , '李四');
insert into Teacher values('03' , '王五');
create table SC(sid varchar(10),cid varchar(10),score decimal(18,1));
insert into SC values('01' , '01' , 80);
insert into SC values('01' , '02' , 90);
insert into SC values('01' , '03' , 99);
insert into SC values('02' , '01' , 70);
insert into SC values('02' , '02' , 60);
insert into SC values('02' , '03' , 80);
insert into SC values('03' , '01' , 80);
insert into SC values('03' , '02' , 80);
insert into SC values('03' , '03' , 80);
insert into SC values('04' , '01' , 50);
insert into SC values('04' , '02' , 30);
insert into SC values('04' , '03' , 20);
insert into SC values('05' , '01' , 76);
insert into SC values('05' , '02' , 87);
insert into SC values('06' , '01' , 31);
insert into SC values('06' , '03' , 34);
insert into SC values('07' , '02' , 89);
insert into SC values('07' , '03' , 98);
首先将学号和学生姓名,课程编号和课程姓名结合起来。使用3张表inner join连表查询
select
s.sid '学号',
s.sname '姓名',
c.cname,
b.score
from
Student as s
INNER JOIN SC as b on s.sid=b.sid
INNER JOIN Course as c on b.cid=c.cid
查询结果:
使用case when 对c.cname进行判断,使用max()函数和sum()函数均可实现行到列的转换。
max(case c.cname when '语文' then b.score else null end) '语文成绩',
上述这一句:
因为按sid分组以后,每名学生的语文成绩只有一个,使用max()和sum()结果都是唯一的那个语文成绩。
如果课程名=“语文”,就取对应的分数,否则为null(表示没考试,可根据实际情况写else的内容)
select
s.sid '学号',
s.sname '姓名',
max(case c.cname when '语文' then b.score else null end) '语文成绩',
max(case c.cname when '数学' then b.score else null end) '数学成绩',
sum(case c.cname when '英语' then b.score else null end) '英语成绩'
from
Student as s
INNER JOIN SC as b on s.sid=b.sid
INNER JOIN Course as c on b.cid=c.cid
GROUP BY s.sid