【问题标题】:Oracle SQL - Count based on a condition to include distinct rows with zero matchesOracle SQL - 根据条件计数以包含零匹配的不同行
【发布时间】: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


    【解决方案1】:

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

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

    如果您有另一个表,每个 id 有一行,我建议您:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      • 2013-09-06
      相关资源
      最近更新 更多