-2

我正在尝试根据第二张桌子上每个班级注册的学生人数来显示表格中的数据。前任:

表格1:

ClassID:  SLN:   Capacity:
1         ABCD       4
2         EFGH       20
3         IJKL       25
4         MNOP       20
5         QRST       25 
6         UVWX       25

表 2:

StudentID:   Class:    
1             ABCD  
3             DCAB   
2             ABCD  
4             ABCD  
5             ABCD
6             EFGH

所以我想要的输出是:

ClassID:  SLN:   Capacity:
2         EFGH       20
3         IJKL       25
4         MNOP       20
5         QRST       25
6         UVWX       25

所以类可以出现在一个表中,但不能出现在另一个表中。我不希望表 2 中的类不在表 1 中,但我确实希望表 1 中的类而不是表 2 中的类。我也不希望显示已满的类。谢谢

4

1 回答 1

1

如果我理解您的要求是正确的,我认为您可以使用以下内容:

select t1.classid, t1.sln, t1.capacity
from table1 t1
where not exists (select 1  -- classes not in table2
                  from table2 t2
                  where t1.sln = t2.class)
  or t1.capacity > (select count(*)  -- classes where capacity not met
                    from table2 t2
                    where t1.sln = t2.class
                    group by class);

请参阅带有演示的 SQL Fiddle

于 2013-05-10T17:45:21.123 回答