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
#