简体   繁体   English

MySQL 中两个日期列之间的平均天数

[英]Average number of days between two date columns in MySQL

I need to find the average number of days between date_a and date_b , across all rows.我需要在所有行中找到date_adate_b之间的平均天数。

row date_a日期_a date_b日期_b
1 1个 2011-01-04 2011-01-04 2014-01-04 2014-01-04
2 2个 2018-12-22 2018-12-22 2021-11-19 2021-11-19
3 3个 2010-03-14 2010-03-14 2011-01-01 2011-01-01

The average number of days between date_a and date_b for this set is 817.3该集合的date_adate_b之间的平均天数是 817.3

There are around 10k rows in the table.表中大约有 10k 行。 Columns date_a and date_b are indexed.date_adate_b已编入索引。

What's the most efficient way of handling this, in a single query?在单个查询中处理此问题的最有效方法是什么?

First of all you can use DATEDIFF() function to calculate difference between two days and then AVG() function to get average of differences:首先,您可以使用DATEDIFF() function 计算两天之间的差异,然后使用AVG() function 获取差异的平均值:

SELECT AVG(DATEDIFF(date_b, date_a)) as average_days FROM table_name;

UPDATE:更新:

One more way is to sum up all differences and then divide by count of all rows:另一种方法是对所有差异求和,然后除以所有行的计数:

SELECT SUM(DATEDIFF(date_b, date_a))/COUNT(*) as average_days FROM table_name;

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

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