我是PostgreSQL的新手(特别是我使用时间刻度数据库),有一个关于时间窗口的问题。
数据:
date |customerid|names
2014-01-01|1 |Andrew
2014-01-02|2 |Pete
2014-01-03|2 |Andrew
2014-01-04|2 |Steve
2014-01-05|2 |Stef
2014-01-06|3 |Stef
2014-01-07|1 |Jason
2014-01-08|1 |Jason 问题是:回到时间x天(从每一行来看),有多少不同的名称共享相同的id?
对于x=2 days,结果应该如下所示:
date |customerid|names |count
2014-01-01|1 |Andrew |1
2014-01-02|2 |Pete |1
2014-01-03|2 |Andrew |2
2014-01-04|2 |Steve |3
2014-01-05|2 |Stef |3
2014-01-06|3 |Stef |1
2014-01-07|1 |Jason |1
2014-01-08|1 |Jason |1 在PostgreSQL中,在不对每一行使用循环的情况下,这是可能的吗?
补充信息:数据的时间间隔在现实中并不等距。
非常感谢!
发布于 2020-06-19 21:30:49
如果你能使用窗口函数就好了:
select t.*,
count(distinct name) over (partition by id
order by date
range between interval 'x day' preceding and current row
) as cnt_x
from t;可惜,这是不可能的。因此,您可以使用横向联接:
select t.*, tt.cnt_x
from t left join lateral
(select count(distinct t2.name) as cnt_x
from t t2
where t2.id = t.id and
t2.date >= t.date - interval 'x day' and t2.date <= t.date
) tt
on true;为了提高性能,您需要一个关于(id, date, name)的索引。
https://stackoverflow.com/questions/62471237
复制相似问题