この記事の最終更新日: 2023年2月5日
MariaDB 10.3.7以降
WITH dates AS (
SELECT generate_series(
'2023-01-01'::date,
'2023-01-31'::date,
'1 day'
) as date
), hours AS (
SELECT generate_series(
0,
23
) as hour
)
SELECT
dates.date,
hours.hour
FROM
dates
CROSS JOIN
hours
ORDER BY
dates.date,
hours.hour;
MariaDB 10.3.7より古い場合
WITH RECURSIVE `date_list` (`date`) AS (
SELECT '2023-01-01'
UNION ALL
SELECT DATE(`date` + INTERVAL 1 DAY)
FROM `date_list`
WHERE `date` < '2023-01-31'
), `hour_list` (`hour`) AS (
SELECT 0 as `hour`
UNION ALL
SELECT `hour` + 1
FROM `hour_list`
WHERE `hour` < 23
)
SELECT
`date_list`.`date`,
`hour_list`.`hour`
FROM
`date_list`
CROSS JOIN
`hour_list`
ORDER BY
`date_list`.`date`,
`hour_list`.`hour`;
結果
date | hour |
2023-01-01 | 0 |
2023-01-01 | 1 |
2023-01-01 | 2 |
2023-01-01 | 3 |
2023-01-01 | 4 |
2023-01-01 | 5 |
2023-01-01 | 6 |
2023-01-01 | 7 |
2023-01-01 | 8 |
2023-01-01 | 9 |
2023-01-01 | 10 |
2023-01-01 | 11 |
2023-01-01 | 12 |
2023-01-01 | 13 |
2023-01-01 | 14 |
2023-01-01 | 15 |
2023-01-01 | 16 |
2023-01-01 | 17 |
2023-01-01 | 18 |
2023-01-01 | 19 |
2023-01-01 | 20 |
2023-01-01 | 21 |
2023-01-01 | 22 |
2023-01-01 | 23 |
2023-01-02 | 0 |
時間を0埋めにしたい場合
WITH RECURSIVE `date_list` (`date`) AS (
SELECT '2023-01-01'
UNION ALL
SELECT DATE(`date` + INTERVAL 1 DAY)
FROM `date_list`
WHERE `date` < '2023-01-31'
), `hour_list` (`hour`) AS (
SELECT LPAD(0, 2, '0') as `hour`
UNION ALL
SELECT LPAD(`hour` + 1, 2, '0')
FROM `hour_list`
WHERE `hour` < '23'
)
SELECT
`date_list`.`date`,
`hour_list`.`hour`
FROM
`date_list`
CROSS JOIN
`hour_list`
ORDER BY
`date_list`.`date`,
`hour_list`.`hour`;
結果
date | hour |
2023-01-01 | 00 |
2023-01-01 | 01 |
2023-01-01 | 02 |
2023-01-01 | 03 |
2023-01-01 | 04 |
2023-01-01 | 05 |
2023-01-01 | 06 |
2023-01-01 | 07 |
2023-01-01 | 08 |
2023-01-01 | 09 |
2023-01-01 | 10 |
2023-01-01 | 11 |
2023-01-01 | 12 |
2023-01-01 | 13 |
2023-01-01 | 14 |
2023-01-01 | 15 |
2023-01-01 | 16 |
2023-01-01 | 17 |
2023-01-01 | 18 |
2023-01-01 | 22 |
関連記事
大阪のエンジニアが書いているブログ。
コメント