问题
I want to group all reports from a given table named 'reports' by every 15 minutes, including intervals where no reports where filled. Example:
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
After the select query I should have:
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
What I tried is the following query but this doesn't include the missing 15-minute-intervals:
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:
If you really want to do it in mysql, this should work to some extent - depending on how you want to organise your 15 minute intervals. I've given the output as time from | time to | number of reports
because i think its meaningless and even a little deceptive to output a specific timestamp and associate a count of a time range with it.
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;
来源:https://stackoverflow.com/questions/29714350/group-by-timestamp-every-15-minutes-including-missing-entries