2011-10-19 81 views
1

我有一個SQL查詢,如下所示:選擇SQL困擾

select a.class_id, b.std_id, 
    (select count(*) from enrollment where class_id = a.class_id) as class_size, 
    d.admission_id 
    from class a, student b, enrollment c, admission d 
    where 
    c.class_id = a.class_id and 
    c.std_id = d.std_id and 
    c.std_id = b.std_id 
    order by a.class_id; 

結果是:

class_id std_id class_size 
comp100 8080 4 
comp100 8020 4 
comp100 8033 4 
comp100 8111 4 
comp305 8080 4 
comp305 8080 4 
comp305 8020 4 
comp305 8033 4 
comp555 8111 1 
comp672 8080 3 
comp672 8033 3 
comp672 8111 3 

但我只是想顯示的結果之一,如果每班人數超過1

我想這樣做:

class_id std_id class_size 
comp100 8080 4 
comp305 8080 4 
comp555 8111 1 
comp672 8080 3 

思考了一段時間之後,我應該先拿到專櫃,這樣

select enrollment.class_id, count(*) as class_size 
from class, enrollment 
where enrollment.class_id = class.class_id 
group by enrollment.class_id; 

則計數器被檢索如下:

class_id class_size 
comp100 4 
comp305 4 
comp555 1 
comp672 3 
然而

,我不知道如何使用一條SQL語句來實現結果。

我想問一下您的意見,如何修改SQL語句,這樣我就可以只顯示行之一,如果每班人數超過1

也就是說,如果班級規模4,我不想顯示4個結果,相反,我的結果就夠了。

非常感謝!

+0

的數據庫您使用的? –

+0

正在做作業嗎?您的匿名用戶名也表明了這一點,更不用說查詢的性質了(這些老師也非常可預測)。 –

+0

我使用oracle oracle sql plus,這是工作時引發的一個問題。 – user540719

回答

0

這可能不是最漂亮的查詢,但它應該得到你所問的:

select distinct class_id, std_id, class_size 
from (
    select a.class_id, b.std_id, 
     (select count(*) from enrollment where class_id = a.class_id) as class_size, 
     d.admission_id 
    from class a, student b, enrollment c, admission d 
    where 
     c.class_id = a.class_id and 
     c.std_id = d.std_id and 
     c.std_id = b.std_id) subquery1 
where 
    subquery1.class_size > 1 

union all 

select class_id, std_id, class_size 
from (
    select a.class_id, b.std_id, 
     (select count(*) from enrollment where class_id = a.class_id) as class_size, 
     d.admission_id 
    from class a, student b, enrollment c, admission d 
    where 
     c.class_id = a.class_id and 
     c.std_id = d.std_id and 
     c.std_id = b.std_id) subquery2 
where 
    subquery2.class_size = 1 

order by class_id