使用分析函数 (PARTITION BY) 和 GROUP BY 的组合:
with v_data as (
select 1 id, 'A' letter, 1 num from dual union all
select 2 id, 'A' letter, 2 num from dual union all
select 3 id, 'A' letter, 3 num from dual union all
select 4 id, 'B' letter, 1 num from dual union all
select 5 id, 'C' letter, 1 num from dual union all
select 6 id, 'C' letter, 2 num from dual
)
select letter, sum(cnt1) as cnt1, sum(cnt2) as cnt2, count(*) cnt_overall from (
select v1.*,
sum(case when num = 1 then 1 else 0 end) over (partition by letter) as cnt1,
sum(case when num = 2 then 1 else 0 end) over (partition by letter) as cnt2
from v_data v1
)
group by letter
having sum(cnt1) > 0 and sum(cnt2) > 0
解释:
- 内部查询返回所有行并计算行 id 的 1 / 2 出现次数
- 外部查询计算给定 id 的行数,并删除不具有值 1 和 2 的 id