计算按日期分组的15分钟间隔的数据

时间:2015-04-07 14:08:12

标签: mysql sql

我有以下MySQL表:

+---------------------+-----------+
|      timestamp      | sensor_id |
+---------------------+-----------+
| 2010-04-09 01:42:31 |    M049   |
| 2010-04-09 01:43:31 |    M049   |
| 2010-04-09 01:44:31 |    M049   |
| 2010-04-09 01:59:31 |    M049   |
| 2010-04-10 01:10:31 |    M049   |
| 2010-04-10 01:40:31 |    M049   |
| 2010-04-10 01:42:31 |    M049   |
| 2010-04-11 16:43:31 |    M049   |
+---------------------+-----------+

我知道如何查询数据库以获取特定日间时间间隔的条目计数,并按日期对结果进行分组。

在凌晨1点到下午2点之间查询事件计数的示例如下所示:

SELECT
    date(timestamp) as date,
    count(timestamp) as count
FROM 
    event_data
WHERE 
    EXTRACT(HOUR FROM TIME(timestamp)) BETWEEN 1 AND 14
GROUP BY 
    date

查询返回下表:

+------------+-------+
|    date    | count |
+------------+-------+
| 2010-04-09 |   4   |
| 2010-04-10 |   3   |
+------------+-------+

现在我只想每15分钟算一次活动。 期望的结果是:

+------------+-------+
|    date    | count |
+------------+-------+
| 2010-04-09 |   2   |
| 2010-04-10 |   2   |
+------------+-------+

如何更改查询以获得这些结果?

1 个答案:

答案 0 :(得分:2)

您可以按日期分组并查询所需的小时数。同样,您可以编写一个获取间隔的查询。我将首先编写一个case语句来读取你想要的每一行,然后添加一个列来指定它的小时间隔。 (0:14 - 1,15:29 - 2 ...)像这样:

SELECT timeCol, 
  HOUR(timeCol) AS hour,
  CASE WHEN MINUTE(timeCol) BETWEEN 0 AND 14 THEN 1
  WHEN MINUTE(timeCol) BETWEEN 15 AND 29 THEN 2
  WHEN MINUTE(timeCol) BETWEEN 30 AND 44 THEN 3
  ELSE 4 END AS minute
FROM myTable;

这给你这样的东西:

|      timeCol        | hour | minute |
+---------------------+------+--------+
| 2010-04-09 01:42:31 |  1   |   3    |
| 2010-04-09 01:43:31 |  1   |   3    |
| 2010-04-09 01:44:31 |  1   |   3    |

一旦你拥有了它,你可以在每一天选择不同的小时/分钟对,只要你相应地使用你的WHERE子句,这将给你你想要的东西:

SELECT DATE(timeCol) AS dateCol, COUNT(DISTINCT hour, minute) AS numEvents
FROM(
  SELECT timeCol, 
    HOUR(timeCol) AS hour,
    CASE WHEN MINUTE(timeCol) BETWEEN 0 AND 14 THEN 1
    WHEN MINUTE(timeCol) BETWEEN 15 AND 29 THEN 2
    WHEN MINUTE(timeCol) BETWEEN 30 AND 44 THEN 3
    ELSE 4 END AS minute
  FROM myTable) tmp
WHERE HOUR(timecol) BETWEEN 1 AND 14
GROUP BY dateCol;

以下是SQL Fiddle示例。

我想补充一点,你不必将间隔记录为1,2,3,4。确保使用可读的东西,将来再次对你有意义。例如,也许这样的事情会更好:

WHEN MINUTE(timeCol) BETWEEN 0 and 14 THEN 'firstInterval'...