4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Oracle SQL 連番や連続した日付を取得

Last updated at Posted at 2018-02-09
-- こんな感じで連番や連続した日付を取得できる。
--

-- 連番(昇順)
SET PAGESIZE 100
-- NUMBER型で
-- NUMBER_FROM <= 範囲 <= NUMBER_TO
SELECT A.NUMBER_FROM + ROWNUM - 1 AS NUMBERS
FROM(
    SELECT -10 AS NUMBER_FROM  -- first number
         ,  10 AS NUMBER_TO    -- last number
    FROM DUAL
    ) A
CONNECT BY LEVEL <= A.NUMBER_TO - A.NUMBER_FROM + 1 ;

   NUMBERS
----------
       -10
        -9
        -8
        -7
        -6
        -5
        -4
        -3
        -2
        -1
         0
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10

21行が選択されました

-- 連番(降順)
SELECT A.NUMBER_FROM - ROWNUM + 1 AS NUMBERS  -- DESCENDING
FROM(
    SELECT  10 AS NUMBER_FROM  -- first number
         , -10 AS NUMBER_TO    -- last number
    FROM DUAL
    ) A
CONNECT BY LEVEL <= A.NUMBER_FROM - A.NUMBER_TO + 1 ;

   NUMBERS
----------
        10
         9
         8
         7
         6
         5
         4
         3
         2
         1
         0
        -1
        -2
        -3
        -4
        -5
        -6
        -7
        -8
        -9
       -10

21行が選択されました。


ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY/MM/DD HH24:MI:SS' ;

-- 連続した日付(昇順)
-- DATE型で
-- DATE_FROM <= 範囲 <= DATE_TO
SELECT A.DATE_FROM + ROWNUM - 1 AS DATES
FROM(
    SELECT TO_DATE('2018/02/25', 'YYYY/MM/DD') AS DATE_FROM
         , TO_DATE('2018/03/05', 'YYYY/MM/DD') AS DATE_TO
    FROM DUAL
    ) A
CONNECT BY LEVEL <= A.DATE_TO - A.DATE_FROM + 1 ;

DATES
-------------------
2018/02/25 00:00:00
2018/02/26 00:00:00
2018/02/27 00:00:00
2018/02/28 00:00:00
2018/03/01 00:00:00
2018/03/02 00:00:00
2018/03/03 00:00:00
2018/03/04 00:00:00
2018/03/05 00:00:00

9行が選択されました。

-- 連続した日付(降順)
SELECT A.DATE_FROM - ROWNUM + 1 AS DATES -- DESCENDING
FROM(
    SELECT TO_DATE('2020/03/05', 'YYYY/MM/DD') AS DATE_FROM
         , TO_DATE('2020/02/25', 'YYYY/MM/DD') AS DATE_TO
    FROM DUAL
    ) A
CONNECT BY LEVEL <= A.DATE_FROM - A.DATE_TO + 1 ;

DATES
-------------------
2020/03/05 00:00:00
2020/03/04 00:00:00
2020/03/03 00:00:00
2020/03/02 00:00:00
2020/03/01 00:00:00
2020/02/29 00:00:00
2020/02/28 00:00:00
2020/02/27 00:00:00
2020/02/26 00:00:00
2020/02/25 00:00:00

10行が選択されました。

-- なお、西暦0年は存在しないとか、
-- ユリウス暦からグレゴリオ暦切り替えのため1582年10月4日(木)の翌日を1582年10月15日(金)に調整されたのは当SQLでは対応していない。

-- Oracle 以外のデータベースでCONNECT BY LEVELが使えるかは未確認。

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?