现有一个student表包含姓名,学号,一个sc表包含学号,成绩,课号,用sql语句检索“001”号课成绩比“003”号课成绩高的所有学生的学号、姓名、001号课程成绩和002号课程成绩及成绩差
时间: 2024-10-19 09:13:43 浏览: 31
第三章SQL数据查询单表查询优秀文档.ppt
你可以使用SQL的JOIN和条件查询来完成这个任务。假设`student`表名为`T_student`,`sc`表名为`T_sc`,并且`student`表中的主键为`sid`(学生ID),`sc`表中的关联字段为`sno`(学号)。下面是一个示例的SQL语句:
```sql
SELECT T_student.sid, T_student.name,
T_sc.score AS score_001,
COALESCE(T_sc.score_002, 0) AS score_002,
(COALESCE(T_sc.score_001, 0) - COALESCE(T_sc.score_003, 0)) AS score_difference
FROM T_student
LEFT JOIN (
SELECT sno, '001' as course_code, score as score_001
FROM T_sc
WHERE course_code = '001'
) sc1 ON T_student.sid = sc1.sno
LEFT JOIN (
SELECT sno, '002' as course_code, score as score_002
FROM T_sc
WHERE course_code = '002'
) sc2 ON T_student.sid = sc2.sno
LEFT JOIN (
SELECT sno, '003' as course_code, score as score_003
FROM T_sc
WHERE course_code = '003'
) sc3 ON T_student.sid = sc3.sno
WHERE T_sc1.score > T_sc3.score;
```
这个查询首先通过LEFT JOIN将学生表与每门课程的成绩表连接起来,并获取了学生001号和002号课程的成绩。然后筛选出001号成绩大于003号的成绩的学生。如果某个学生没有某门课程的成绩,`COALESCE`函数会返回0。
阅读全文