选择SQL麻烦

时间:2011-10-19 11:44:09

标签: 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个结果,相反,我的结果就足够了。

非常感谢!

1 个答案:

答案 0 :(得分: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