首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用PL/SQL分析来依赖子字符串?

使用PL/SQL分析来依赖子字符串?
EN

Stack Overflow用户
提问于 2021-10-20 16:29:34
回答 1查看 50关注 0票数 0

如何编写查询以返回以K开头的农场的计数

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

代码语言:javascript
复制
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;

期望结果

代码语言:javascript
复制
 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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-20 17:52:57

下面是解决问题的解决方案,它应该比当前的方法更快(更有效)。请注意,这里这两个解析函数只由id分区;条件计数是在count()调用本身中单独处理的。而且,对K或k的比较都是不区分大小写的;在您尝试的查询中,有一个比较不敏感。我也避免正则表达式(更慢),因为这里不需要正则表达式。

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69649794

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档