第3章 SQL 習題 - 3.11
阿新 • • 發佈:2018-11-19
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)