简体   繁体   English

MySQL每月平均datediff

[英]MySQL average datediff per month

I have for example following databse: 例如,我有以下数据库:

date1      | date2      | datediff
2016-11-02 | 2016-11-05 | 3
2016-11-08 | 2016-11-10 | 2
2016-11-01 | 2016-11-05 | 4
2016-11-09 | 2016-11-09 | 0
2016-11-15 | 2016-11-20 | 5

I get the datediff with following sql: 我通过以下sql获得datediff:

select 
datediff(date2, date1)
from table

Now I need the average datediff for each month, in this case for 2016-11: 2.8 现在我需要每个月的平均datediff,在这种情况下,是2016-11年的:2.8

Thanks in advance, Patrick. 预先感谢,帕特里克。

you can use month(), AVG and group by 您可以使用month(),AVG和分组依据

select year(date1), month(date1), avg(datediff(date2, date1))
from my_table 
group by year(date1), month(date1)
;

I think you can just use group by : 我认为您可以使用group by

select year(date1), month(date1), AVG(datediff(date2, date1))
from table
group by year(date1), month(date1);
select AVG(datediff(date2, date1))
from table
group by year(date1), month(date1);

You can get the last day of the month for any date / time value with the LAST_DAY() function . 您可以使用LAST_DAY()函数获取任何日期/时间值的月份的最后一天。 (It sounds more apocalyptic than it is.) That's useful for grouping. (听起来比世界末日要残酷得多。)这对于分组很有用。

So, try 所以,尝试

 SELECT LAST_DAY(date1) month_ending, AVG(DATEDIFF(date2,date1)) datediff
   FROM table
  GROUP BY LAST_DAY(date1)
  ORDER BY LAST_DAY(date1)
select avg(datediff(date2, date1))as difference
from table
group by year(date1),month(date1)

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

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