Oracle SQL - 根据条件进行计数以包括具有零个匹配项的不同行

Oracle SQL - Count based on a condition to include distinct rows with zero matches

是否有一种“更好”的方法来重构下面的查询 returns 每个不同 id 特定值(例如 'A')的出现次数?挑战似乎是将 id = 2 保留在结果集中,即使计数为零(id = 2'A' 无关)。它有常用的table表达式、NVL函数、内联视图、distinct和left join。完成这项工作真的需要所有这些吗? (甲骨文 19c)

create table T (id, val) as
  select 1, 'A' from dual
  union all select 1, 'B' from dual
  union all select 1, 'A' from dual
  union all select 2, 'B' from dual
  union all select 2, 'B' from dual
  union all select 3, 'A' from dual
;

with C as (select id, val, count(*) cnt from T where val = 'A' group by id, val)
select D.id, nvl(C.cnt, 0) cnt_with_zero from (select distinct id from T) D left join C on D.id = C.id
order by id
;

        ID CNT_WITH_ZERO
---------- -------------
         1             2
         2             0
         3             1

一种简单的方法是条件聚合:

select id,
       sum(case when val = 'A' then 1 else 0 end) as num_As
from t
group by id;

如果您有另一个 table 每个 ID 一行,我建议您:

select i.id,
       (select count(*) from t where t.id = i.id and t.val = 'A') as num_As
from ids i;