【MariaDB】指定の日付と0〜23までの時間帯が一式揃ったカラムを簡単に作成するSQL【SELECT】

dates times hours sql select yurupro SQL
この記事は約4分で読めます。

この記事の最終更新日: 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`;

結果

datehour
2023-01-010
2023-01-011
2023-01-012
2023-01-013
2023-01-014
2023-01-015
2023-01-016
2023-01-017
2023-01-018
2023-01-019
2023-01-0110
2023-01-0111
2023-01-0112
2023-01-0113
2023-01-0114
2023-01-0115
2023-01-0116
2023-01-0117
2023-01-0118
2023-01-0119
2023-01-0120
2023-01-0121
2023-01-0122
2023-01-0123
2023-01-020
以降も2023-01-31 23まで続く

時間を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`;

結果

datehour
2023-01-0100
2023-01-0101
2023-01-0102
2023-01-0103
2023-01-0104
2023-01-0105
2023-01-0106
2023-01-0107
2023-01-0108
2023-01-0109
2023-01-0110
2023-01-0111
2023-01-0112
2023-01-0113
2023-01-0114
2023-01-0115
2023-01-0116
2023-01-0117
2023-01-0118
2023-01-0122
以降も2023-01-31 23まで続く

関連記事

コメント

タイトルとURLをコピーしました