P粉4329300812023-08-31 09:26:55
要么
WITH RECURSIVE cte AS ( SELECT 0 `hour` UNION ALL SELECT `hour` + 1 FROM cte WHERE `hour` < 23 ) SELECT cte.`hour`, COUNT(test.id) `count` FROM cte LEFT JOIN test ON cte.`hour` >= HOUR(test.start_at) AND cte.`hour` < HOUR(test.end_at) GROUP BY 1 ORDER BY 1;
要么
WITH RECURSIVE cte AS ( SELECT CAST('00:00:00' AS TIME) `hour` UNION ALL SELECT `hour` + INTERVAL 1 HOUR FROM cte WHERE `hour` < '23:00:00' ) SELECT cte.`hour`, COUNT(test.id) `count` FROM cte LEFT JOIN test ON cte.`hour` >= test.start_at AND cte.`hour` < test.end_at GROUP BY 1 ORDER BY 1;
第一个查询以时间格式返回小时列,而第二个查询以数值形式返回此列。选择对您来说安全的变体。
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=5a77b6e3158be06c7a551cb7e64673de