红移-按类别查找贡献百分比

dm7nw8vv  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(464)

我的数据格式如下:

product, person
prod_a, person_1
prod_a, person_2
prod_a, person_3
prod_b, person_1

我试图找出每个人对每个产品的贡献百分比。预期输出为:

product, person, prct
prod_a, person_1, 0.33
prod_a, person_2, 0.33
prod_a, person_3, 0.33
prod_b, person_1, 1
wlwcrazw

wlwcrazw1#

可以使用窗口函数:

select
    product,
    person,
    1.0 * count(*) over(partition by product, person) 
        / count(*) over(partition by product) as prct
from mytable

如示例数据所示,如果没有重复的 (product, person) 元组,那么就简单一点:

select
    product,
    person,
    1.0 / count(*) over(partition by product) as prct
from mytable

相关问题