首页 > 解决方案 > 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 中是否可能而不在每一行上使用循环?

附加信息:数据的时间间隔实际上并不是等距的。

非常感谢你!

标签: sqlpostgresqltimescaledb

解决方案


如果您可以使用窗口函数,那就太好了:

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).


推荐阅读