【发布时间】:2021-03-26 15:42:15
【问题描述】:
是否有一种“更好”的方法来重构下面的查询,该查询返回每个不同 id 的特定值(例如 'A')的出现次数?挑战似乎是将id = 2 保留在结果集中,即使计数为零(id = 2 从未与'A' 相关)。它具有公用表表达式、NVL 函数、内联视图、不同和左连接。完成这项工作真的需要所有这些吗? (甲骨文 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
【问题讨论】:
标签: sql oracle count analytic-functions