mysql求平均时间间隔,MySQL:记录间的平均间隔

Assume this table:

id date

----------------

1 2010-12-12

2 2010-12-13

3 2010-12-18

4 2010-12-22

5 2010-12-23

How do I find the average intervals between these dates, using MySQL queries only?

For instance, the calculation on this table will be

(

( 2010-12-13 - 2010-12-12 )

+ ( 2010-12-18 - 2010-12-13 )

+ ( 2010-12-22 - 2010-12-18 )

+ ( 2010-12-23 - 2010-12-22 )

) / 4

----------------------------------

= ( 1 DAY + 5 DAY + 4 DAY + 1 DAY ) / 4

= 2.75 DAY

解决方案

Intuitively, what you are asking should be equivalent to the interval between the first and last dates, divided by the number of dates minus 1.

Let me explain more thoroughly. Imagine the dates are points on a line (+ are dates present, - are dates missing, the first date is the 12th, and I changed the last date to Dec 24th for illustration purposes):

++----+---+-+

Now, what you really want to do, is evenly space your dates out between these lines, and find how long it is between each of them:

+--+--+--+--+

To do that, you simply take the number of days between the last and first days, in this case 24 - 12 = 12, and divide it by the number of intervals you have to space out, in this case 4: 12 / 4 = 3.

With a MySQL query

SELECT DATEDIFF(MAX(dt), MIN(dt)) / (COUNT(dt) - 1) FROM a;

This works on this table (with your values it returns 2.75):

CREATE TABLE IF NOT EXISTS `a` (

`dt` date NOT NULL

) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `a` (`dt`) VALUES

('2010-12-12'),

('2010-12-13'),

('2010-12-18'),

('2010-12-22'),

('2010-12-24');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值