postgresql SQL/PSQL:创建一个列,其值为“满足某个条件的所有情况之和”,按行排列

yhuiod9q  于 2023-03-12  发布在  PostgreSQL
关注(0)|答案(1)|浏览(99)

很抱歉取了这么难听的名字。我不知道该怎么说才好。
我在SQL(postgres)中有以下CTE

product     payments instances
Professional   3        1
Professional   4        1
Starter        1        29
Starter        2        8
Starter        3        4
Team           1        1
Team           2        2

它的基本意思是:
product计划中的instances用户支付了payments笔款项。
我需要对此进行转换,使其成为支付X次的用户数,而不是支付X次的用户数。
预期结果:

product     payments instances
Professional   1        2
Professional   2        2
Professional   3        2
Professional   4        1
Starter        1        41
Starter        2        12
Starter        3        4
Starter        4        0
Team           1        3
Team           2        2
Team           3        0
Team           4        0

不同的是,现在,(例如)支付了2次的用户也被计入支付了1次的用户数量中......因为从逻辑上讲,如果你支付了2次,你也至少支付了1次。
我现在的情况是:

with pay_counts as (
    {{#102}}
),
plan_pay_counts as (
    select
        plan,
        payments,
        count(plan) as number_of_users
    from 
        pay_counts
    group by
        plan, payments
),
i as (
    SELECT 
        generate_series(1,max(payments)) as payments
    FROM 
        pay_counts
)
select * from plan_pay_counts
order by plan, payments;

理论上,i将是表示付款次数的列。

nxowjjhe

nxowjjhe1#

下面回答我自己的问题。我通过使用交叉联接获得了所需的结果,这样我就可以对每一行执行计算,然后重新分组。使用以下代码:

with pay_counts as (
    {{#102}}
),
plan_pay_counts as (
    select
        plan,
        payments,
        count(plan) as number_of_users
    from 
        pay_counts
    group by
        plan, payments
),
i as (
    SELECT 
        generate_series(1,max(payments)) as payments
    FROM 
        pay_counts
),
long_form as (
    select 
        plan,
        i.payments as index_payments,
        sum(case when ppc.payments >= i.payments then number_of_users else 0 end) as number_of_users
    from 
        plan_pay_counts ppc cross join i
    group by
        plan, i.payments, ppc.payments
    order by 
        plan, i.payments, ppc.payments
)
select
    plan,
    index_payments as payments,
    sum(number_of_users) as number_of_users
from
    long_form
group by
    plan, index_payments

相关问题