以下是 BigQuery 标准 SQL
#standardSQL
WITH minmax AS (
SELECT MIN(test) AS mintest, MAX(test) AS maxtest, 5 AS step
FROM `project.dataset.table`
), intervals AS (
SELECT
TIMESTAMP_ADD(mintest, INTERVAL step * num MINUTE) AS test1,
TIMESTAMP_ADD(mintest, INTERVAL step * 60* (1 + num) - 1 SECOND) AS test2
FROM minmax,
UNNEST(GENERATE_ARRAY(0, DIV(TIMESTAMP_DIFF(maxtest, mintest, MINUTE) , step))) AS num
)
SELECT test1, test2, SUM(hd_count) AS hd_count
FROM intervals JOIN `project.dataset.table`
ON test BETWEEN test1 AND test2
GROUP BY test1, test2
您可以使用下面的虚拟数据测试/玩上面的内容
#standardSQL
WITH `project.dataset.table` AS (
SELECT TIMESTAMP '2013-12-20 10:40:30' test, 1 hd_count UNION ALL
SELECT TIMESTAMP '2013-12-20 10:41:30', 3 UNION ALL
SELECT TIMESTAMP '2013-12-20 10:42:30', 2 UNION ALL
SELECT TIMESTAMP '2013-12-20 10:43:30', 1 UNION ALL
SELECT TIMESTAMP '2013-12-20 10:44:30', 1 UNION ALL
SELECT TIMESTAMP '2013-12-20 10:45:30', 3 UNION ALL
SELECT TIMESTAMP '2013-12-20 10:46:30', 2 UNION ALL
SELECT TIMESTAMP '2013-12-20 10:47:30', 1
), minmax AS (
SELECT MIN(test) AS mintest, MAX(test) AS maxtest, 5 AS step
FROM `project.dataset.table`
), intervals AS (
SELECT
TIMESTAMP_ADD(mintest, INTERVAL step * num MINUTE) AS test1,
TIMESTAMP_ADD(mintest, INTERVAL step * 60* (1 + num) - 1 SECOND) AS test2
FROM minmax,
UNNEST(GENERATE_ARRAY(0, DIV(TIMESTAMP_DIFF(maxtest, mintest, MINUTE) , step))) AS num
)
SELECT test1, test2, SUM(hd_count) AS hd_count
FROM intervals JOIN `project.dataset.table`
ON test BETWEEN test1 AND test2
GROUP BY test1, test2
ORDER BY test1
输出如下
test1 test2 hd_count
2013-12-20 10:40:30 UTC 2013-12-20 10:45:29 UTC 8
2013-12-20 10:45:30 UTC 2013-12-20 10:50:29 UTC 6