GROUP BY时间戳每15分钟一次,包括缺少的条目

时间:2015-04-18 07:29:51

标签: mysql select group-by timestamp

我希望每隔15分钟对名为“报告”的给定表格中的所有报告进行分组,包括没有填充报告的时间间隔。例如:

id      timestamp 
---------------------------
1        2015-04-16 20:52:04
2        2015-04-16 20:53:04
3        2015-04-16 20:54:04
4        2015-04-16 19:52:04
5        2015-04-17 22:24:56
6        2015-04-17 22:27:09
7        2015-04-18 06:48:41

在选择查询之后,我应该:

timestamp       count
----------------------
20:52:04         3
21:07:04         0
21:22:04         0
21:37:04         0
21:52:04         0
22:07:04         0
22:22:04         2
22:37:04         0
22:52:04         0
......
06:52:04         1
07:07:04         0

我尝试的是以下查询,但这不包括缺少的15分钟间隔:

select created_at , count(id) AS count 
from `reports` 
where `company_id` = '3' 
group by UNIX_TIMESTAMP(created_at) DIV 900 
order by `created_at` asc

1 个答案:

答案 0 :(得分:0)

如果你真的想在mysql中这样做,这应该在某种程度上起作用 - 取决于你想要如何组织你的15分钟间隔。我已将输出设为time from | time to | number of reports,因为我认为输出特定的时间戳并将时间范围的计数与其关联起来毫无意义甚至有点欺骗性。

SELECT CONCAT (
        lpad(hours.a, 2, "0"),
        ":",
        lpad(minutes.a * 15, 2, "0"),
        ":00"
        ) AS 'from',
    CONCAT (
        lpad(hours.a, 2, "0"),
        ":",
        lpad((minutes.a * 15) + 14, 2, "0"),
        ":59"
        ) AS 'to',
    count(r.id)
FROM (
    SELECT 0 AS a

    UNION

    SELECT 1 AS a

    UNION

    SELECT 2 AS a

    UNION

    SELECT 3 AS a

    UNION

    SELECT 4 AS a

    UNION

    SELECT 5 AS a

    UNION

    SELECT 6 AS a

    UNION

    SELECT 7 AS a

    UNION

    SELECT 8 AS a

    UNION

    SELECT 9 AS a

    UNION

    SELECT 10 AS a

    UNION

    SELECT 11 AS a

    UNION

    SELECT 12 AS a

    UNION

    SELECT 13 AS a

    UNION

    SELECT 14 AS a

    UNION

    SELECT 15 AS a

    UNION

    SELECT 16 AS a

    UNION

    SELECT 17 AS a

    UNION

    SELECT 18 AS a

    UNION

    SELECT 19 AS a

    UNION

    SELECT 20 AS a

    UNION

    SELECT 21 AS a

    UNION

    SELECT 22 AS a

    UNION

    SELECT 23 AS a
    ) hours
INNER JOIN (
    SELECT 0 AS a

    UNION

    SELECT 1 AS a

    UNION

    SELECT 2 AS a

    UNION

    SELECT 3 AS a
    ) minutes
LEFT JOIN reports r ON hours.a = hour(r.t)
    AND minutes.a = floor(minute(r.t) / 15)
GROUP BY hours.a,
    minutes.a;