Postgres累计金额超过前几个月

时间:2017-01-28 22:12:37

标签: postgresql

我有一个表,该月有%的用户。我想添加这些百分比以获得该月的累积总和。我不认为我的累积功能是正确的。

因此,第5行应显示cum_amt 0.1381 ...
第4行,0.1381 + 0.010169 = 0.148,
等...

但第1行应该是0.164 bc它不是bayside

enter image description here

select 
    created, name, new_users, possible, 
    (new_users::FLOAT / possible) as penetration,
    sum((new_users::FLOAT / possible)) OVER (ORDER BY created) AS cum_amt

from 
    mom_users

where 
    new_users > 10

order by
    name, created
    desc

2 个答案:

答案 0 :(得分:1)

我认为你需要{/ 1}}和分析后的分析功能:

partition by

答案 1 :(得分:0)

我认为此代码适合您。

CREATE TABLE mom_users (
created timestamp,
name text,
new_users int,
possible int
);

insert into mom_users values('2016-11-01 00:00:00', 'banning', 11, 67);
insert into mom_users values('2016-10-01 00:00:00', 'bayside', 253, 1180);
insert into mom_users values('2016-09-01 00:00:00', 'bayside', 92, 1180);
insert into mom_users values('2016-06-01 00:00:00', 'bayside', 12, 1180);
insert into mom_users values('2016-05-01 00:00:00', 'bayside', 163, 1180);

SELECT *, new_users/possible::real penetration, sum(new_users/possible::real) OVER (PARTITION BY name ORDER BY CREATED) cum_amt 
FROM mom_users 
WHERE new_users > 10
ORDER BY created DESC;