【问题标题】:Get average time difference grouped by another column in postgresql获取按postgresql中另一列分组的平均时间差
【发布时间】:2021-07-17 21:13:30
【问题描述】:

我有一个帖子表,我有兴趣计算每个作者帖子之间的平均差异。这是一个最小的例子:

+---------------+---------------------+
| post_author   | post_date           |
|---------------+---------------------|
| 0             | 2019-03-05 19:12:24 |
| 1             | 2017-11-06 18:28:43 |
| 1             | 2017-11-06 18:28:43 |
| 1             | 2017-11-06 18:28:43 |
| 1             | 2017-11-06 18:28:43 |
| 1             | 2018-02-19 18:36:36 |
| 1             | 2018-02-19 18:36:36 |
| 1             | 2018-02-19 18:36:36 |
| 1             | 2018-02-19 18:36:36 |
| 1             | 2018-02-19 18:40:09 |
+---------------+---------------------+

所以对于每个作者,我想从本质上获取他们的时间序列的增量,然后找到平均值(按作者分组)。所以最终结果看起来像:

+---------------+---------------------+
| post_author   | post_date_delta(hrs)|
|---------------+---------------------|
| 0             | 0                   |
| 1             | 327                 |
| 2             | 95                  |
| ...           | ...                 |
+---------------+---------------------+

我可以想到如何在 Python 中执行此操作,但我正在努力编写一个(postgres)SQL 查询来完成此操作。任何帮助表示赞赏!

【问题讨论】:

    标签: sql postgresql time-series


    【解决方案1】:

    您可以使用聚合和算术:

    select post_author,
           (max(post_date) - min(post_date)) / nullif(count(*) - 1, 0)
    from t
    group by post_author;
    

    平均天数是最大天数和最小天数之差除以计数减一。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      • 2011-02-12
      相关资源
      最近更新 更多