我有一个表格,其中包含用户ID和他们加入的时间戳数据。 如果我需要按月份显示数据,我可以使用以下方法:
select
count(user_id),
date_trunc('month',(to_timestamp(users.timestamp))::timestamp)::date
from
users
group by 2
日期截断代码允许使用“second”、“day”、“week”等。因此,我可以按这些时间段对数据进行分组。如何按“n-day”周期(例如45天)对数据进行分组?基本上,我需要显示每个45天周期的用户数量。欢迎任何建议或指导!目前我得到的是:
Date Users
2015-03-01 47
2015-04-01 72
2015-05-01 123
2015-06-01 132
2015-07-01 136
2015-08-01 166
2015-09-01 129
2015-10-01 189
我希望数据以45天为间隔传输。就像这样:-
Date Users
2015-03-01 85
2015-04-15 157
2015-05-30 192
2015-07-14 229
2015-08-28 210
2015-10-12 294
更新:
我使用如下代码获取输出,但仍存在一个问题,即我得到的值有偏差。
with
new_window as (
select
generate_series as cohort
, lag(generate_series, 1) over () as cohort_lag
from
(
select
*
from
generate_series('2015-03-01'::date, '2016-01-01', '45 day')
)
t
)
select
--cohort
cohort_lag -- This worked. !!!
, count(*)
from
new_window
join users on
user_timestamp <= cohort
and user_timestamp > cohort_lag
group by 1
order by 1
但是我得到的输出是:
Date Users
2015-04-15 85
2015-05-30 157
2015-07-14 193
2015-08-28 225
2015-10-12 210
基本上,2015年3月1日显示的用户应该是2015年3月1日至2015年4月15日之间的用户,依此类推。
但是我似乎获得了截止到某个日期的用户价值。也就是说:截至2015年4月15日,有85个用户。这不是我想要的结果。需要帮助吗?