我想每15分钟对一个名为“reports”的给定表中的所有报告进行分组,包括不填写报告的间隔。例子:
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
最佳答案
如果你真的想在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;