我有一张如下表格:
id letter number
1 A 1
2 A 2
3 A 3
4 B 1
5 C 1
6 C 2
我需要计算字母A的数字,其中字母A的数字为1 OR 2.这很简单,我就明白了。但现在我需要计算id,其中字母A的数字为 AND 数字2,等等。然后每个字母都相同。所以我会得到:
letter count
A 3
C 2
我不关心B,因为计数是1.谢谢。
答案 0 :(得分:1)
使用分析函数(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
说明: