consider the following schema (primary keys are underlined): Student (sname, sid, gpa, level, deptno) Course (cno, cname, deptno, units) Dept (dname, deptno) Takes (sid, cno) Write a SQL query that returns the names (i.e., snames) of students who have taken more courses outside their department than inside their department. For this question, you can assume that all students in the database have taken at least one course inside their department
时间: 2024-03-27 16:36:16 浏览: 62
Here's a SQL query that should achieve the desired result:
```
SELECT s.sname
FROM Student s
INNER JOIN Takes t ON s.sid = t.sid
INNER JOIN Course c ON t.cno = c.cno
WHERE c.deptno <> s.deptno
GROUP BY s.sid, s.sname
HAVING COUNT(CASE WHEN c.deptno <> s.deptno THEN 1 END) > COUNT(CASE WHEN c.deptno = s.deptno THEN 1 END)
```
Explanation:
- We join the `Student`, `Takes`, and `Course` tables together using their respective keys.
- We filter the joined table to only include rows where the course department is different from the student's department (`c.deptno <> s.deptno`).
- We group the rows by student ID and name, and use the `HAVING` clause to filter to only those students who have taken more courses outside their department than inside. We achieve this by using `COUNT(CASE WHEN...)` to count the number of courses taken inside and outside the student's department, respectively.
Note that this query assumes that each student has taken at least one course inside their department. If this is not the case, some students may be excluded from the results.
阅读全文