如何计算两个日期之间的每小时,每日,每月和每年平均值?

时间:2014-01-31 11:51:11

标签: php mysql

我正在用PHP开发一个应用程序。我使用MySql数据库。我想在两个日期之间计算每小时每日每月每年平均

我对小时平均值的查询是

SELECT avg(value) 
FROM table_name  
WHERE (added_date BETWEEN '2014-01-29 00:00:00' AND '2014-01-31 00:00:00') 
GROUP BY DATE(added_date), HOUR(added_date)  
ORDER BY added_date ASC

现在我想做同样的查询来计算每日,每月和每年的平均值。 请建议解决方案。感谢

1 个答案:

答案 0 :(得分:1)

你的意思是这些吗?

每小时平均值

SELECT DATE(added_date), HOUR(added_date) , avg(value) 
FROM table_name  
WHERE (added_date BETWEEN '2013-01-29 00:00:00' AND '2014-01-31 00:00:00') 
GROUP BY DATE(added_date), HOUR(added_date)  
ORDER BY added_date ASC

每日平均值

SELECT DATE(added_date) , avg(value) 
FROM table_name  
WHERE (added_date BETWEEN '2013-01-29 00:00:00' AND '2014-01-31 00:00:00') 
GROUP BY DATE(added_date)
ORDER BY added_date ASC

每月平均值

SELECT YEAR(added_date), MONTH(added_date), avg(value) 
FROM table_name  
WHERE (added_date BETWEEN '2013-01-29 00:00:00' AND '2014-01-31 00:00:00') 
GROUP BY YEAR(added_date), MONTH(added_date)
ORDER BY added_date ASC

年度平均值

SELECT YEAR(added_date), avg(value) 
FROM table_name  
WHERE (added_date BETWEEN '2013-01-29 00:00:00' AND '2014-01-31 00:00:00') 
GROUP BY YEAR(added_date)  
ORDER BY added_date ASC