获取按postgresql中另一列分组的平均时间差

时间:2021-04-23 16:29:29

标签: sql postgresql time-series

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

+---------------+---------------------+
| 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 查询来实现这一点。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

您可以使用聚合和算术:

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

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

相关问题