【发布时间】: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