在SQL中只选择完整的组?

时间:2015-01-05 21:15:09

标签: sql oracle11g grouping

假设有2个表,如下所示。表A包含几个组中的行 - 在这种情况下为11(1,2,3)和22(4,5,6,7)。表B包含通过B.a_id = A.a_id外键关系间接引用表A中的组的书行:

Table A:
a_id  grp
---------
1     11
2     11
3     11

4     22
5     22
6     22
7     22

Table B:
b_id a_id book
--------------
1    1    AA
2    2    AA
3    3    AA

4    1    BB
5    2    BB
6    3    BB

7    1    CC
8    3    CC

9    4    AA
10   5    AA
11   6    AA

12   4    BB
13   5    BB
14   6    BB
15   7    BB

16   6    CC
17   7    CC

我只需要选择那些完整的书籍/组合组合,即

a_id  grp  book
---------------
1     11   AA
2     11   AA
3     11   AA

1     11   BB
2     11   BB
3     11   BB

4     22   BB
5     22   BB
6     22   BB
7     22   BB
11 CC,22 AA或22 CC不符合条件,因为它们不代表完整的组。 获得所需结果的一种方法是在子查询中使用每个组的行计数,但它看起来有些不稳定。还有其他想法吗?

谢谢!

编辑:我不认为引用的问题确实是同一个问题。

1 个答案:

答案 0 :(得分:0)

这是我能想到的:

select
  A.a_id, A.grp, B.book
from
  A
  inner join B
  on A.a_id = B.a_id

  left outer join
  (select distinct A.grp, B.book
   from A, B
   where not exists
    (
    select *
    from A a2
      inner join B b2
      on a2.a_id = b2.a_id
    where
      a2.a_id = A.a_id
      and a2.grp = A.grp
      and b2.book = B.book
    )
  ) T1 -- < -- represents incomplete book/group combos
  on A.grp = T1.grp
  and B.book = T1.book
where
  T1.grp is null -- < -- exclude incomplete book/group combos