MySQL每15分钟计算一次Averge

时间:2018-09-17 10:56:41

标签: sql date datetime group-by mariadb

嗨,我有一个类似的表格:

CREATE TABLE `data` (
 `time` DATETIME NOT NULL.
 `cpu` DECIMAL(10, 4) UNSIGNED NOT NULL
)

例如,我每10秒就有一行。

time                    cpu     
2018-09-12 11:49:41     0.200
2018-09-12 11:49:51     0.100
2018-09-12 11:50:01     0.200
2018-09-12 11:50:11     0.301
2018-09-12 11:50:21     0.100
2018-09-12 11:50:31     0.000
2018-09-12 11:50:41     0.200
2018-09-12 11:50:51     0.100
2018-09-12 11:51:01     0.100
2018-09-12 11:51:11     0.400
2018-09-12 11:51:21     0.000
2018-09-12 11:51:31     0.000
2018-09-12 11:51:41     0.300
2018-09-12 11:51:51     0.300
2018-09-12 11:52:01     0.300
2018-09-12 11:52:11     0.200
2018-09-12 11:52:21     0.000
2018-09-12 11:52:31     0.200
2018-09-12 11:52:41     0.100
2018-09-12 11:52:51     0.200
2018-09-12 11:53:01     0.801
2018-09-12 11:53:11     0.100
2018-09-12 11:53:21     0.200
2018-09-12 11:53:31     0.200
2018-09-12 11:53:41     0.100

我想每15分钟计算一次CPU平均值。我该怎么办?

提前谢谢!

我正在使用:

MariaDB [(none)]> SELECT VERSION();
+----------------------------------+
| VERSION()                        |
+----------------------------------+
| 10.1.30-MariaDB-0ubuntu0.17.10.1 |
+----------------------------------+
1 row in set (0.00 sec)

1 个答案:

答案 0 :(得分:1)

您可以将time截断为15分钟的边界(零秒,减去15分钟的模数15分钟),然后按结果值分组:

SELECT clamped_time, AVG(cpu) AS average_cpu
FROM (
    SELECT
        time
        - INTERVAL EXTRACT(SECOND FROM time) SECOND
        - INTERVAL EXTRACT(MINUTE FROM time) % 15 MINUTE AS clamped_time,
        cpu
    FROM data
) AS sq
GROUP BY clamped_time