【问题标题】:Using PL/SQL Analytics to Count on Substring?使用 PL/SQL 分析来计算子字符串?
【发布时间】:2021-12-07 11:59:17
【问题描述】:

我应该如何编写查询以返回以 K 开头的农场的计数 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

【问题讨论】:

  • 那么,有什么要求呢?返回输入数据,添加一列,在 FARM 名称以 K 开头的行上显示 K_COUNT,否则为 0? (而且,从您的尝试看来,匹配的 K 应该不区分大小写?)您为什么要按 ID 分区 - 这是要求的一部分吗?如果是,为什么在问题的“英语”部分没有说明?在任何情况下,您的计数都会返回 1,因为 SUBSTR(..., 1) 仅表示整个字符串。 1 作为第二个参数表示“从哪个位置” - 你可能想要 SUBSTR(..., 1, 1) - second 1 表示长度。
  • 要求:如果 Farm 以字母 K 开头,则将其添加到 K_count。 Farm 以字母 K 开头的三个记录。所以我希望 K_count 计算为 3 而不是 1。
  • Substr(...1,1) 是解决方案.. 谢谢
  • 如果substr(..., 1, 1) 解决了你的问题,那么它是低效的。即使您必须按 id 进行分区(您也没有将其包含在上面评论中的“要求”中),您也不应该进一步按substr(.....) 进行分区。相反,您应该使用条件计数:count (case when ... then 1 end) over (partition by id) 比您当前的方法更有效。
  • 我正在按 ID b/c 进行分区我想在每个 ID 处捕获农场计数。这是要求的一部分。它不区分大小写,因此以 K 或 k 开头的 Farm 相同。

标签: sql plsql substring analytics oracle12c


【解决方案1】:

这是一个解决您的问题的解决方案,应该比您当前的方法更快(更有效)。请注意,这里的两个分析函数都仅按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

【讨论】:

    猜你喜欢
    • 2019-06-29
    • 2013-02-05
    • 2021-01-06
    • 1970-01-01
    • 2019-05-28
    • 2018-11-10
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    相关资源
    最近更新 更多