找出具体的团体Oralce

时间:2016-02-11 07:05:33

标签: sql oracle

我在表SUBJECT_GRP

的PK中有以下数据
GRP_ID    SUBJECT
1         Comp Science
2         Comp Science
2         Math
2         Physics
3         Chemistry
3         Math
3         Physics

我在逻辑

中使用以下查询
SELECT RELATIVE_GROUPS.GRP_ID
FROM (SELECT GRP_ID, count(1) ALL_CNT 
      FROM SUBJECT_GRP GROUP BY GRP_ID) ALL_GROUPS,
     (SELECT GRP_ID, count(1) RELATIVE_CNT
      FROM SUBJECT_GRP 
      WHERE ((INSTR(:sqli_subject, '@' || RTRIM(SUBJECT) || '@', 1, 1) > 0 ))
      GROUP BY GRP_ID) RELATIVE_GROUPS
WHERE ALL_GROUPS.GRP_ID = RELATIVE_GROUPS.GRP_ID
  AND ALL_CNT = RELATIVE_CNT

For :sqli_subject = '@Comp Science@Math@Physics@'

我只想要组1和组2作为输出。有人有效率地做到这一点吗?

1 个答案:

答案 0 :(得分:0)

您的查询工作正常,另一种方法是在分析版本中使用count,这样表格只会被点击一次:

select distinct grp_id 
  from (
    select grp_id, subject, count(1) over (partition by grp_id) cnt1,  
           count(case when instr('@Comp Science@Math@Physics@', 
                           '@' || rtrim(subject) || '@', 1, 1) > 0 
                      then 1 end) over (partition by grp_id) cnt2
      from subject_grp )
  where cnt1 = cnt2

测试数据:

create table subject_grp(grp_id number(3), subject varchar2(20));
insert into subject_grp values (1, 'Comp Science' );
insert into subject_grp values (2, 'Comp Science' );
insert into subject_grp values (2, 'Math' );
insert into subject_grp values (2, 'Physics' );
insert into subject_grp values (3, 'Chemistry' );
insert into subject_grp values (3, 'Math' );
insert into subject_grp values (3, 'Physics' );