这是数据库表:
student_id 学生ID
course_id 课程ID
score 分数
查询课程ID为“1”比课程ID为“2”成绩高的所有学生的学号,SQL语句怎么写?
这是数据库表:
student_id 学生ID
course_id 课程ID
score 分数
查询课程ID为“1”比课程ID为“2”成绩高的所有学生的学号,SQL语句怎么写?
可以考虑先行转列,即把数据行课程转换为列(课程1和课程2),然后从结果集中查询符合课程ID为“1”比课程ID为“2”成绩高
1、创建表,比如表名student_score
CREATE TABLE `student_score` (
`id` int(11) DEFAULT NULL,
`student_id` varchar(255) DEFAULT NULL COMMENT '学生id''',
`course_id` varchar(255) DEFAULT NULL COMMENT '课程id',
`score` int(11) DEFAULT NULL COMMENT '分数'
) ENGINE=InnoDB DEFAULT CHARSET=utf8
2、插入测试数据
insert into `test`.`student_score` ( `id`, `course_id`, `score`, `student_id`) values ( '1', '1', '80', '001');
insert into `test`.`student_score` ( `id`, `course_id`, `score`, `student_id`) values ( '2', '2', '78', '001');
insert into `test`.`student_score` ( `id`, `course_id`, `score`, `student_id`) values ( '3', '3', '90', '001');
insert into `test`.`student_score` ( `id`, `course_id`, `score`, `student_id`) values ( '4', '1', '90', '002');
insert into `test`.`student_score` ( `id`, `course_id`, `score`, `student_id`) values ( '5', '2', '95', '002');
insert into `test`.`student_score` ( `id`, `course_id`, `score`, `student_id`) values ( '6', '1', '90', '003');
insert into `test`.`student_score` ( `id`, `course_id`, `score`, `student_id`) values ( '7', '2', '88', '003');
测试数据:
3、执行sql,
SELECT * from(
SELECT student_id,sum(case when course_id = '1' then score else 0 end) AS course1,
sum(case when course_id = '2' then score else 0 end) AS course2
from student_score GROUP BY student_id) sc
where sc.course1>sc.course2
结果: