【问题标题】:Time window in PostgreSQLPostgreSQL 中的时间窗口
【发布时间】:2020-10-09 18:21:57
【问题描述】:

我是 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 中是否可以在每一行上不使用循环?

附加信息:数据的时间间隔在现实中并不是等距的。

非常感谢!

【问题讨论】:

    标签: sql postgresql timescaledb


    【解决方案1】:

    如果可以使用窗口函数就好了:

    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) 上建立索引。

    【讨论】:

    • 是的,COUNT() 是在 windows 函数中实现的,但不是 COUNT(DISTINCT &lt;column&gt;)。横向查询就是解决办法。
    • 非常感谢!在过去的几周里,我使用 Spark 来计算这样的查询,我很好奇这在 PostgrSQL 中是否也同样可能。
    • 如我所见,在大数据(+200k 行)上,这不会执行。在您看来,什么样的数据库解决方案适合这些问题?
    • @Dominik 。 . .根据您拥有的 id 数量,索引应该会有很大帮助。
    • 是的,我明白了。但是我有多个查询(它们都相似但仍然不同)。最后我会得到一堆索引,我认为这会导致问题。表格中的每一行都是一次购买交易。
    猜你喜欢
    • 2021-05-12
    • 2023-03-23
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 2017-10-18
    相关资源
    最近更新 更多