运行 在 pgsql 中计算速率

Run rate calculate in pgsql

我有这个table:

CREATE TABLE data 
    (
        Event_Date date,
        approved int, 
        rejected int
    )
    
    INSERT INTO data (Event_date, approved, rejected)
    VALUES
        ('20190910', '5', '2'),
        ('20190911', '6', '3'),
        ('20190912', '5', '2'),
        ('20190913', '7', '5'),
        ('20190914', '8', '4'),
        ('20190915', '10', '2'),
        ('20190916', '4', '1')

如何制作循环或其他东西来计算 运行 率并获得结果(在滚动月率 CL 中,我写了如何使用公式),如下所示:

Event_date   approved,      rejected    Rolling monthly rate
------------------------------------------------------------
20190901           5           2           ---
20190902           6           3           6+5/5+6+2+3
20190903           4           2           6+4/6+3+4+2
20190903           7           5           7+4/4+2+7+5
20190904           8           4           8+4/7+5+8+4
20190905           10          2           ....
20190906           4           1           .....

lag() 函数,returns 以前的值,非常适合这个任务。 您需要编写 case when 语句并跳过第一个条目,因为没有先前的值,然后使用所需的公式进行计算。

select *, case when row_number() over() > 1
          then  approved + lag(approved) over() / approved + rejected + lag(approved)  over() + lag(rejected)  over()
          end   as rate
from my_table

演示在 DBfiddle