sql - PostgreSQL 中的时间窗口
问题描述
我是 PostgreSQL 的新手(具体来说,我使用 Timescale db)并且对时间窗口有疑问。
数据:
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 天,结果应如下所示:
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 中是否可能而不在每一行上使用循环?
附加信息:数据的时间间隔实际上并不是等距的。
非常感谢你!
解决方案
如果您可以使用窗口函数,那就太好了:
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)
.
推荐阅读
- python - SQLAlchemy:运行聚合函数
- javascript - 如何在 Reactjs 中加密和解密对象数据
- javascript - Google 身份服务 - 保持登录状态
- python - Crontab Django Management 命令似乎已启动,但没有任何反应
- c++ - cin>>x 如何在 if(cin>>x) 中返回 bool 类型值,但在 cout<<(cin>>x);
- python - 记录到多个文件和控制台
- react-native - 如何通过移动手机在本机反应中制作倾斜动画
- reactjs - AgGrid 26 服务器端数据源不会停止加载行
- reactjs - 我是 React 钩子的新手,并尝试使用此代码提交表单。我收到此错误
- grpc - 客户端拦截器错误:没有请求的半关闭