按周累计总数 - postgresql

时间:2017-09-02 11:17:12

标签: postgresql join count group-by postgresql-9.5

使用postgresql,版本9.5.8

下面我有一个有效的查询,它为我提供了所有帐户的现成帐户的pct。然后按周拆分此表,为我提供当周创建的帐户数量,随后就绪。

查询如下:

SELECT 
               date_trunc('week', al.created_at) as week_created,
               count(case when ra.status='ready' then 1 end) as total_accounts,
               count(case when ra.status='ready' AND ra.tests > 0 then 1 end) as accounts_ready,
               concat(round(count(case when ra.status='ready' AND ra.tests > 0 then 1 end) :: decimal /count(case when ra.status='ready' then 1 end) :: decimal * 100.0), '%') as pct_accounts_ready

    FROM "ready_accounts" ra
    JOIN "accounts_list" al
    ON al.id=ra.id
    GROUP BY week_created
    ORDER BY week_created DESC;

结果设置如下:

周创建---------总帐户----帐户就绪---- Pct帐户就绪

Monday 14 Aug ----  50 ----------------39 ---------------- 78%
Monday 7 Aug  ----  20 ----------------10 ---------------- 20%

麻烦的是,我得到的结果不是累积的,他们只是一周,这对我想要实现的目标毫无意义。

我想要一个显示的结果集:

Monday 14 Aug ---  70 ------------------- 49 ---------------- 70%
Monday 7 Aug  ---  20 ------------------- 10 ---------------- 20%

示例输入数据:

示例数据如下所示: 准备账户表:

ra.id   ra.status   ra.tests
123     ready       1
124     not_ready   2
125     not_ready   0
126     ready       1
127     ready       0
128     ready       0
129     ready       1

帐户清单表:

al.id   al.created_at

123     Monday 14 August
124     Monday 7 August
125     Monday 14 August
126     Monday 14 August
127     Monday 7 August
128     Monday 14 August
129     Monday 31 July

我尝试了很多解决方案,但我遇到了问题。任何解决方案的例子都会非常有用!

提前谢谢你。 我对此很陌生,所以任何解释都会有用!

1 个答案:

答案 0 :(得分:1)

在派生表(FROM子句中的子查询)中使用不带最后一列的查询,并使用sum()作为窗口函数。计算外部包装查询中的百分比:

select 
    week_created,
    total_accounts,
    accounts_ready,
    concat((accounts_ready/ total_accounts* 100)::int, '%') as pct_accounts_ready
from (
    select
        week_created,
        sum(total_accounts) over w as total_accounts,
        sum(accounts_ready) over w as accounts_ready
    from (
        select 
            date_trunc('week', al.created_at) as week_created,
            count(case when ra.status='ready' then 1 end) as total_accounts,
            count(case when ra.status='ready' and ra.tests > 0 then 1 end) as accounts_ready
        from "ready_accounts" ra
        join "accounts_list" al
        on al.id=ra.id
        group by week_created
        ) s
    window w as (order by week_created)
    ) s
order by week_created desc;