1、建表
成绩表:
create table if not exists user_count (
userid int(2),
course varchar(5),
score int(3)
);
insert into user_count values(1,'语文',60,default);
insert into user_count values(1,'数学',30,default);
insert into user_count values(1,'英语',71,default);
insert into user_count values(2,'语文',30,default);
insert into user_count values(2,'数学',60,default);
insert into user_count values(2,'英语',81,default);
insert into user_count values(3,'语文',70,default);
insert into user_count values(3,'数学',80,default);
insert into user_count values(3,'英语',91,default);
学生信息表:
create table if not exists userinfo(
id int(4) primary key auto_increment,
name varchar(10),
tel varchar(11)
) charset utf8;
insert into userinfo values(default,'ldw','1867700');
insert into userinfo values(default,'ch','18632700');
insert into userinfo values(default,'fj','1867322700');
2、关联查询
select us.id 学号,us.name 姓名,
sum( case uc.course when '语文' then uc.score else 0 end) as 语文,
sum( case uc.course when '数学' then uc.score else 0 end) as 数学,
sum( case uc.course when '英语' then uc.score else 0 end) as 英语,
sum(uc.score) as 总分
from user_count uc
left outer join userinfo us on us.id = uc.userid
group by us.id,us.name order by sum(uc.score) desc;