使用 PL/SQL 分析来计算子字符串?

Using PL/SQL Analytics to Count on Substring?

对于以 K 开头的农场,我应该如何为 return 计数 3

为什么(partition by id,substr(farm,1))计算为1

with tree_harvest
as ( 
select 1 as id, 'PINE' as tree, 'K001' as farm from dual union all
select 1 as id, 'PINE' as tree, '0003' as farm from dual union all
select 1 as id, 'PINE' as tree, 'K002' as farm from dual union all
select 1 as id, 'PINE' as tree, 'K003' as farm from dual
)
select id, tree,farm,
       count(*) over (partition by id) as id_count,
       case
       when regexp_like(farm,'^K','i') 
       then count(*) over (partition by id,substr(farm,1))
       else 0
       end as k_count
       from tree_harvest;

   
   

想要的结果

 ID TREE FARM   ID_COUNT  K_COUNT  
  1 PINE  0003  4         0
  1 PINE  K001  4         3
  1 PINE  K002  4         3
  1 PINE  K003  4         3

这是解决您的问题的解决方案,应该比您当前的方法更快(更有效)。请注意,这里两个分析函数仅按 id 划分;条件计数在 count() 调用本身中单独处理。与 K 或 k 的比较也不区分大小写;在您尝试的查询中,其中一项比较不是。我也避免了这里不需要的正则表达式(较慢)。

with tree_harvest
as ( 
select 1 as id, 'PINE' as tree, 'K001' as farm from dual union all
select 1 as id, 'PINE' as tree, '0003' as farm from dual union all
select 1 as id, 'PINE' as tree, 'K002' as farm from dual union all
select 1 as id, 'PINE' as tree, 'K003' as farm from dual
)
select id, tree,farm,
       count(*) over (partition by id) as id_count,
       case when lower(farm) like 'k%' then
           count(case when lower(farm) like 'k%' then 1 end) 
                over (partition by id) else 0 end as k_count
       from tree_harvest;
       
        ID TREE FARM   ID_COUNT    K_COUNT
---------- ---- ---- ---------- ----------
         1 PINE K001          4          3
         1 PINE K003          4          3
         1 PINE K002          4          3
         1 PINE 0003          4          0