Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

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

The average number of days between date_a and date_b for this set is 817.3

There are around 10k rows in the table. Columns date_a and date_b are indexed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What’s the most efficient way of handling this, in a single query?

>Solution :

First of all you can use DATEDIFF() function to calculate difference between two days and then AVG() function to get average of differences:

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading