在我的PostgreSQL数据库中,我有一个包含以下字段的邀请表:
Invitations: id, created_at, completed_at
我正在编写一个PostgreSQL查询,该查询按每周同类群组细分数据,并在created_at的1天之内(在1-2天至3天或更长时间之间)显示完成时间的细分。完成时间基于字段completed_at
所需输出:
weeks_ago | start | end | Total | % Completed in Day 1 | % Completed in D2 | % Completed 3 or days later
0 | 2020-02-04 | 2020-02-11 | ?% | ?% | ?%
1 | 2020-01-28 | 2020-02-03 | ?% | ?% | ?%
[这是我到目前为止的内容:
SELECT TRUNC(DATE_PART('day', CURRENT_DATE - i.created_at )/7) AS weeks_ago,
date(min(i.created_at)) AS "start",
date(max(i.created_at)) AS "end",
count(DISTINCT i.id) AS "total",
FROM invitations i
GROUP BY weeks_ago
ORDER BY weeks_ago ASC;
鉴于上面的查询,如何添加以下内容?
谢谢
嗯。 。 。这似乎是条件聚合:
select date_trunc('week', i.created_at) as week_start,
date_trunc('week', i.created_at) + interval '6 day' as week_end,
floor( (date_trunc('week', current_date) - date_trunc('week', i.created_at) / 7) as weeks ago,
avg( (i.completed_at <= i.started_at + interval '1 day')::int ) as percent_1,
avg( (i.completed_at <= i.started_at + interval '2 day' and i.started_at > i.start_at + interval '1' day >)::int ) as percent_2,
avg( (i.completed_at > i.started_at + interval '2 day')::int ) as percent_3plus
from invitations i
group by week_start, week_end, weeks_ago
order by weeks_ago asc;