【问题标题】:Cumulative total by week - postgresql按周累计 - postgresql
【发布时间】:2018-02-11 06:49:24
【问题描述】:

使用 postgresql,版本 9.5.8

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

以下查询:

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

我尝试了多种解决方案,但都卡住了。任何解决方案示例都会非常有帮助!

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

【问题讨论】:

  • 如果没有看到您的输入数据,可能很难调试您的查询。您能否为您的问题提供一个最小且可重复的样本?
  • 没有。删除上述评论并将该数据放入您的问题中。
  • 完成 - @TimBiegeleisen

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


【解决方案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;

【讨论】:

  • 谢谢。我认为它不起作用,因为关系“week_created”来自我已与子查询中的表连接的另一个表。如果您查看我的原始查询,我会通过将另一个表 ('accounts_list') 加入到 'ready_accounts' 表中来获得 week_created。我想我需要在最后一个子查询中保留一个联接?
  • 很好 - 这太棒了,给了我想要的结果。非常感谢!!
猜你喜欢
  • 1970-01-01
  • 2021-11-10
  • 2011-08-07
  • 2014-05-15
  • 2021-06-07
  • 2014-05-02
  • 2020-04-08
  • 2022-10-25
相关资源
最近更新 更多