我给你四张表,表结构是第一张表名称是student,字段是 s_id,s_name,s_birth,s_sex; 第二张表名称是teacher字段是t_id,t_name 第三张表名称是course,字段是 c_id,c_name,t_id; 第四张表名称是score,表字段是 s_id,c_id,s_score,根据以上表结构生成难度高的oracle sql题目及答案
时间: 2024-02-19 08:03:19 浏览: 66
假设四张表的表结构如下:
```
CREATE TABLE student (
s_id INT PRIMARY KEY,
s_name VARCHAR2(50),
s_birth DATE,
s_sex VARCHAR2(10)
);
CREATE TABLE teacher (
t_id INT PRIMARY KEY,
t_name VARCHAR2(50)
);
CREATE TABLE course (
c_id INT PRIMARY KEY,
c_name VARCHAR2(50),
t_id INT,
CONSTRAINT fk_teacher FOREIGN KEY (t_id) REFERENCES teacher(t_id)
);
CREATE TABLE score (
s_id INT,
c_id INT,
s_score INT,
CONSTRAINT pk_score PRIMARY KEY (s_id, c_id),
CONSTRAINT fk_student FOREIGN KEY (s_id) REFERENCES student(s_id),
CONSTRAINT fk_course FOREIGN KEY (c_id) REFERENCES course(c_id)
);
```
现在给出以下复杂的 Oracle SQL 题目和答案:
1. 查询每门课程的平均分和最高分,按照平均分从高到低排序。
答案:
```
SELECT c.c_id, c.c_name, AVG(s.s_score) AS avg_score, MAX(s.s_score) AS max_score
FROM course c
LEFT JOIN score s ON c.c_id = s.c_id
GROUP BY c.c_id, c.c_name
ORDER BY avg_score DESC;
```
2. 查询每个学生的平均成绩,按照平均成绩从高到低排序。
答案:
```
SELECT s.s_id, s.s_name, AVG(sc.s_score) AS avg_score
FROM student s
LEFT JOIN score sc ON s.s_id = sc.s_id
GROUP BY s.s_id, s.s_name
ORDER BY avg_score DESC;
```
3. 查询没有选修任何课程的学生的姓名和性别。
答案:
```
SELECT s.s_name, s.s_sex
FROM student s
LEFT JOIN score sc ON s.s_id = sc.s_id
WHERE sc.s_id IS NULL;
```
4. 查询同时选修了编号为 1 和编号为 2 课程的学生的姓名。
答案:
```
SELECT s.s_name
FROM student s
INNER JOIN score sc ON s.s_id = sc.s_id
WHERE sc.c_id IN (1, 2)
GROUP BY s.s_id, s.s_name
HAVING COUNT(DISTINCT sc.c_id) = 2;
```
5. 查询选修了所有课程的学生的姓名。
答案:
```
SELECT s.s_name
FROM student s
INNER JOIN score sc ON s.s_id = sc.s_id
GROUP BY s.s_id, s.s_name
HAVING COUNT(DISTINCT sc.c_id) = (SELECT COUNT(*) FROM course);
```
这些题目和答案都比较复杂,需要熟练掌握 SQL 查询和连接的知识才能解决。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)