使时间间隔mysql的值的平均值

时间:2017-12-15 09:12:43

标签: mysql sql timestamp average

我有这张桌子:

`Telegramas` (`Id`, `Fecha`, `Valor_Dispositivo`) VALUES
(1, '2017-12-14 11:06:01.6976', '5'),
(2, '2017-12-14 11:07:01.4561', '2'),
(3, '2017-12-14 11:08:01.1651', '6'),
(4, '2017-12-14 12:06:01.2146', '1'),
(5, '2017-12-14 12:40:01.7981', '9');

我需要这样的退出:

2017-12-14 11:00:00.0000 -> 4.33
2017-12-14 12:00:00.0000 -> 5

我需要每小时按日期列计算时间间隔来计算数据的平均值。

这是我的查询,我很丢失。我需要帮助。

SELECT TIME(DATE_SUB(Telegramas.Fecha,INTERVAL (MINUTE(Telegramas.Fecha)%20) MINUTE)) as tiempo, SUM(IFNULL(Telegramas.Valor_Dispositivo,0)) as suma FROM Telegramas GROUP BY Fecha ORDER BY Telegramas.ID_Auto DESC;

3 个答案:

答案 0 :(得分:2)

一种方法是从date中提取hourtimestamp部分,然后按结果分组。

select DATE_ADD(date(fecha), INTERVAL EXTRACT(HOUR FROM fecha) HOUR) as FECHA_DATE_HOUR, 
       avg(Valor_Dispositivo) as Valor_Dispositivo
from Telegramas
group by date(fecha), EXTRACT(HOUR FROM fecha);

<强>结果:

+---------------------+-------------------+
|   FECHA_DATE_HOUR   | Valor_Dispositivo |
+---------------------+-------------------+
| 14.12.2017 11:00:00 | 4.3333            |
| 14.12.2017 12:00:00 | 5.0000            |
+---------------------+-------------------+

<强> DEMO

答案 1 :(得分:1)

我会利用函数DATE_FORMAT并转换类型datetime:

DATE_FORMAT(CURRENT_TIMESTAMP, '%Y-%m-%d %H:00:00');

在你的例子中:

SELECT AVG(`Valor_Dispositivo`), DATE_FORMAT(`Fecha`, '%Y-%m-%d %H:00:00') `by_hour` 
FROM `Telegramas` 
GROUP BY 2;

答案 2 :(得分:1)

试试这个:一种简单的方法可以帮到你

SELECT CONCAT(DATE(Fecha), ' ', HOUR(Fecha),':00:00.0000') Fecha, 
    AVG(valor_Dispositivo) average
FROM Telegramas
GROUP BY DATE(Fecha), HOUR(Fecha)