如何编写查询以返回以K开头的农场的计数
为什么(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发布于 2021-10-20 17:52:57
下面是解决问题的解决方案,它应该比当前的方法更快(更有效)。请注意,这里这两个解析函数只由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 0https://stackoverflow.com/questions/69649794
复制相似问题