PostgreSQL 中的时间窗口

Dom*_*nik 4 sql postgresql timescaledb

我是 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 
Run Code Online (Sandbox Code Playgroud)

问题是:回到 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  
Run Code Online (Sandbox Code Playgroud)

在 PostgreSQL 中,这是否可能无需在每一行上使用循环?

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

非常感谢!

Gor*_*off 6

如果你能使用窗口函数那就太好了:

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;
Run Code Online (Sandbox Code Playgroud)

唉,这是不可能的。所以你可以使用横向连接:

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;
Run Code Online (Sandbox Code Playgroud)

为了提高性能,您需要在 上建立索引(id, date, name)