Oracle Analytics获取汇总计数

z31licg0  于 2023-02-07  发布在  Oracle
关注(0)|答案(1)|浏览(171)

对于这个查询,如何获得每个Tree_ID的汇总计数?

with tree_row
as (
select '1111' as tree_id, 'PULP' as tree_product from dual union all
select '1111' as tree_id, 'PULP' as tree_product from dual union all
select '2222' as tree_id, 'PULP' as tree_product from dual union all
select '2222' as tree_id, 'CHIP' as tree_product from dual union all
select '3333' as tree_id, 'PULP' as tree_product from dual union all
select '3333' as tree_id, 'CHIP' as tree_product from dual union all
select '3333' as tree_id, 'CHIP' as tree_product from dual
)
select distinct tree_id, 
       count(*) over (partition by tree_id, tree_product) as pulp_count,
       count(*) over (partition by tree_id, tree_product) as chip_count,
       count(*) over (partition by tree_id)               as tree_total
       from tree_row;

预期结果

TREE_ID PULP_COUNT  CHIP_COUNT TREE_TOTAL
    1111     2           0            2
    2222     1           1            2
    3333     1           2            3
jjjwad0x

jjjwad0x1#

您不需要分析函数,可以使用条件聚合-正常聚合,但要使用case表达式(条件部分)来确定要包含在计数中的行:

with tree_row
as (
select '1111' as tree_id, 'PULP' as tree_product from dual union all
select '1111' as tree_id, 'PULP' as tree_product from dual union all
select '2222' as tree_id, 'PULP' as tree_product from dual union all
select '2222' as tree_id, 'CHIP' as tree_product from dual union all
select '3333' as tree_id, 'PULP' as tree_product from dual union all
select '3333' as tree_id, 'CHIP' as tree_product from dual union all
select '3333' as tree_id, 'CHIP' as tree_product from dual
)
select tree_id, 
       count(case when tree_product = 'PULP' then tree_id end) as pulp_count,
       count(case when tree_product = 'CHIP' then tree_id end) as chip_count,
       count(*)                                                as tree_total
       from tree_row
       group by tree_id;

| 树ID|纸浆计数|芯片计数|树_总计|
| - ------|- ------|- ------|- ------|
| 小行星|第二章|无|第二章|
| 小行星2222|1个|1个|第二章|
| 小行星3333|1个|第二章|三个|
fiddle

相关问题