我是SQL的新手,所以这个问题可能很愚蠢。
以下是相关表格的示例行: 学生:
+-------+----------+---------+------+------+-------+---------+-----------+
| StuID | LName | Fname | Age | Sex | Major | Advisor | city_code |
+-------+----------+---------+------+------+-------+---------+-----------+
| 1001 | Smith | Linda | 18 | F | 600 | 1121 | BAL |
Minor_in:
+-------+------+
| StuID | DNO |
+-------+------+
| 1004 | 520 |
百货商店:
+------+----------+--------------------------+------+--------------+--------+
| DNO | Division | DName | Room | Building | DPhone |
+------+----------+--------------------------+------+--------------+--------+
| 10 | AS | History of Art | 268 | Mergenthaler | 7117 |
我想找到CS Major中最受欢迎的学生(DNO = 600) 这是我的查询,它有效,但它很难看:
SELECT DNO, count
FROM (SELECT DNO, COUNT(*) AS count
FROM Minor_in
WHERE StuID IN (SELECT StuID
FROM Student
WHERE (Major = 550 OR Major = 600))
GROUP BY DNO
) AS C1
WHERE count IN (
SELECT MAX(count)
FROM (
SELECT DNO, COUNT(*) AS count
FROM Minor_in
WHERE StuID IN (SELECT StuID
FROM Student
WHERE (Major = 550 OR Major = 600))
GROUP BY DNO
) AS MinorCount
);
还有更好的方法吗? 非常感谢!
答案 0 :(得分:0)
这个怎么样?
select stuid.dno, count (*)
from stuid inner join student
on stuid.stuid = student.stuid
where student.major in (550, 600)
group by stuid.dno
order by count (*) desc
我假设dnos 550和600是计算机科学课程