简体   繁体   English

如何按日期顺序计算日期之间的平均天数

[英]How to calculate average number of days between dates in date order

Table contains order dates 表格包含订单日期

create table orderdate ( orderdate date not null )

How to calculate average days between dates in table. 如何计算表格中日期之间的平均天数。 Difference needs to be calculated between neighbour dates in date order to find average number of dates between orders. 需要计算日期顺序中相邻日期之间的差异,以找到订单之间的平均日期数。

Adding this number to last order date produces estimated next order date. 将此数字添加到上一个订购日期将产生估计的下一个订购日期。

For example if table contains 例如,如果表包含

2019-09-10
2019-09-21
2019-09-25

differences between orders are 10 and 4 days and average difference is 订单之间的差异为10天和4天,平均差异为

(10+4)/2 = 7 days

next order esimated date is 2019-09-25 + 7 = 2019-10-02 下一个订单的模拟日期为2019-09-25 + 7 = 2019-10-02

Using 使用

PostgreSQL 9.4.19

You can use aggregation: 您可以使用聚合:

select ( max(date) - min(date) ) / nullif(count(*) - 1, 0) as avg_duration
from t;

The number of gaps is one less than the count. 缺口数比计数少一。 Hence the average is the total duration divided by the number of gaps. 因此,平均值是总持续时间除以间隔数。

First calculate the difference between adjacent dates, then take the average: 首先计算相邻日期之间的差,然后取平均值:

SELECT avg(CAST(days_between AS double precision))
FROM (SELECT orderdate
             - (lag(orderdate) OVER (ORDER BY orderdate)) AS days_between
      FROM orderdate) AS q;

I cast to double precision , because the difference between two date s is an integer . 我将double precisiondouble precision ,因为两个date之间的差是integer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM