3.11使用大学模式,用SQL写出如下查询。
a.找出所有至少选修了一门Comp. Sci. 课程的学生姓名,保证结果中没有重复的姓名。
with target_course(id, title) as (
select course_id, title from course where dept_name = 'Comp. Sci.'
)
select distinct name from takes natural join student
where course_id in (select id from target_course);
name
----------
Bourikas
Zhang
Shankar
Williams
Levy
Brown
(6 rows)
b.找出所有没有选修在2009年春季之前开设的任何课程的学生的ID和姓名。
with student_id(ID) as (
(select ID from student)
except -- 减去所有选修2009年春季课程的学生
--找出所有选修2009年春季开设课程的学生
(select distinct ID from takes where (course_id, sec_id, semester, year)
in(
--找出2009年春季开设的所有课程
select course_id, sec_id, semester, year from section where year = 2009 and semester = 'Spring'
)))
select ID, name from student natural join student_id order by ID;
id | name
-------+----------
00128 | Zhang
19991 | Brandt
23121 | Chavez
44553 | Peltier
45678 | Levy
55739 | Sanchez
70557 | Snow
76543 | Brown
98765 | Bourikas
98988 | Tanaka
(10 rows)
c.找出每个系教师的最高工资值。可以假设每个系至少有一位教师。
select dept_name, max(salary) from instructor
group by dept_name;
dept_name | max
------------+-----------
Finance | 90000.00
History | 62000.00
Physics | 95000.00
Music | 40000.00
Comp. Sci. | 101200.00
Biology | 72000.00
Elec. Eng. | 80000.00
(7 rows)
d.从前述查询所计算出的每个系最高工资中选出最低值。
with dept_salary_max(dept_name, salary) as (
select dept_name, max(salary) from instructor
group by dept_name
) select min(salary) from dept_salary_max;
min
----------
40000.00
(1 row)