2013-10-15 60 views
1

我是SQL新手,所以這個問題可能很愚蠢。找到最受歡迎的未成年人CS

下面是相關表的一個樣本行: 學生:

+-------+----------+---------+------+------+-------+---------+-----------+ 
| 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專業(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

謝謝!第一次使用StackOverflow!是要改變格式,但你只是太快了!如果我將stuid作爲Student,再次感謝 – BersaKAIN

回答

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是計算機科學課程

+0

,那麼由於每個學生只能在1個部門主修,所以參加者會給出空集。但是,無論如何感謝 – BersaKAIN

+0

@BersaKAIN:我錯過了這個專業存儲在學生表中的事實。我正在重寫查詢。 –

+0

這將顯示令人敬畏的順序。你知道還有其他方法來獲得最大數量的所有實體嗎? – BersaKAIN