简体   繁体   English

MySql 平均日期差

[英]MySql average date difference

I have a problem and I don't know if it is possible to solve it.我有一个问题,我不知道是否有可能解决它。 Namely, I have a MySQL database with two columns: id and date.即,我有一个 MySQL 数据库,其中包含两列:id 和 date。 How can I formulate a query that will calculate the average difference of all dates?如何制定一个查询来计算所有日期的平均差异? For example, between 1 and 2 the date is 14 days, between 2 and 3 is 12 days so the average will be 13 days.例如,1 到 2 之间的日期为 14 天,2 到 3 之间的日期为 12 天,因此平均值为 13 天。

The average is just the largest value minus the smallest divided by one less than the number of values.平均值只是最大值减去最小值除以值的数量减一。 So:所以:

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

You can easily see this if you look at the numbers:如果您查看数字,您可以很容易地看到这一点:

 1
 5       . . . 4
 10      . . . 5
 19      . . . 9

The average difference is (4 + 5 + 9) / 3 = 6.平均差为 (4 + 5 + 9) / 3 = 6。

It is not a coincidence that (19 - 1) / 3 = 6 as well. (19 - 1) / 3 = 6 也不是巧合。 It is a mathematical certainty.这是一个数学上的确定性。

You can easily see this.你可以很容易地看到这一点。 The average difference is:平均差异为:

( (5 - 1) + (10 - 5) + (19 - 10) ) / 3

You can rearrange this:您可以重新排列:

( -1 + (5 - 5) + (10 - 10) + 19 ) / 3

which is:这是:

( 19 - 1 ) / 3

Hope this will help希望这会有所帮助

SELECT  AVG(DATEDIFF(Date, NextDate)) 
    FROM    (   SELECT  
                        Date,
                        (   SELECT  MIN(Date) 
                            FROM    YourTable T2
                            WHERE   T2.Date > T1.Date
                        ) AS NextDate
                FROM    YourTable T1
            ) AS T

*use your table name for YourTable *使用您的表名作为 YourTable

this works when the there are non overlapping date ranges between two dates in rows.当行中的两个日期之间存在不重叠的日期范围时,此方法有效。 If there are ranges of 0 as well then use >= instead of >如果范围也为 0,则使用 >= 而不是 >

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

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