2012-04-03 54 views
1

我嘗試db-class.org的一些練習videos.There是找到編寫SQL,而無需使用聚合

「誰適用於高校,並選擇 CS爲所有學生的GPA最低的一個問題主要'

使用聚合這是;

select min(gpa) from student,apply where student.sid=apply.sid and major='CS'; 

結果將是

min 
----- 
3.4 
(1 row) 

SID,平均成績表學生而申請表中有場SID,主要

我怎麼能改寫這個不用聚集?

我試圖

select gpa from student,apply where major='CS' and gpa < all(select gpa from student,apply where student.sid=apply.sid and major='CS'); 

但是這給了我一些14行而不是正確的結果 GPA

----- 
2.9 
2.9 
2.9 
2.9 
2.9 
2.9 
2.9 
2.9 
2.9 
2.9 
2.9 
2.9 
2.9 
2.9 
(14 rows) 

爲什麼會出現這種情況?有人可以幫我嗎?

+1

我會使用一個明確的內部連接,而不是那個隱式連接。 – Corbin 2012-04-03 06:58:52

回答

2

試圖重用你的查詢,我認爲你缺少對學生的一個連接,並應用在外部查詢。此外,我認爲你應該使用<=而不是<。另請注意,瞭解您的DBMS將有所幫助。

select gpa from student, apply 
where major='CS' and student.sid = apply.sid and gpa <= all (
    select gpa from student, apply 
    where student.sid = apply.sid and major='CS' 
) 
+0

我正在使用postgres ..thanks ..但是如何<=在這裏工作? – damon 2012-04-03 07:01:54

+1

你會得到一個記錄,並與所有其他人(包括其本身!)進行比較。這個記錄不能低於自身,以便它必須與自身相等。或者,也許我太困了,因爲它的上午4點:) – 2012-04-03 07:06:59

0
select top 1 gpa 
from student, apply 
where student.sid = apply.sid and major='CS' 
order by gpa; 
0
select gpa from student,apply 
where student.sid=apply.sid and major='CS' 
order by gpa limit 1 
+0

這是MySQL的語法,對吧? – bniwredyc 2012-04-03 06:57:21

+0

有沒有辦法用子查詢來做到這一點? – damon 2012-04-03 06:57:36

+0

不,「限制」是針對整個查詢的,而不是針對子查詢的。 – idstam 2012-04-03 11:43:39