简体   繁体   English

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

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

Is there a "better" way to refactor the query below that returns the number occurrences of a particular value (eg 'A' ) for each distinct id ?是否有一种“更好”的方法来重构下面的查询,该查询返回每个不同id的特定值(例如'A' )的出现次数? The challenge seems to be keeping id = 2 in the result set even though the count is zero ( id = 2 is never related to 'A' ).挑战似乎是将id = 2保留在结果集中,即使计数为零( id = 2从未与'A'相关)。 It has a common table expression, NVL function, in-line view, distinct, and left join.它具有公用表表达式 NVL function、内联视图、不同的和左连接。 Is all of that really needed to get this job done?完成这项工作真的需要所有这些吗? (Oracle 19c) (甲骨文 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

A simple way is conditional aggregation:一个简单的方法是条件聚合:

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

If you have another table with one row per id, you I would recommend:如果您有另一个表,每个 id 有一行,我建议您:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM