How to get an array using Oracle SQL query

I want to display the result set Years from From date - To date using oracle SQL on a double table

eg.

if I go from date as 1/1/1900 to date as 1/1/2000

then display will be displayed

Only years

1900
1901
1902
-
-

2000
+3
source share
1 answer

There are two parts to this question. Creating a date range is pretty simple: just use the CONNECT BY trick I demonstrated here .

change

Creating a list of the first days of the New Year is quite simple:

SQL> select add_months(to_date('01-jan-1900'), (level-1)*12) as year
  2  from dual
  3  connect by level <= 101
  4  /

YEAR
---------
01-JAN-00
01-JAN-01
01-JAN-02
...
01-JAN-98
01-JAN-99
01-JAN-00

101 rows selected.

SQL>

Do you just want years? Well, either use to_char(... , 'YYYY'). Or cut to the chase and just generate a list of numbers from 1900 to 2000.

- . , . ...

SQL> select to_char(add_months(to_date('&&start_date'), (level-1)*12), 'YYYY') as year
  2  from dual
  3  connect by level <= ( to_number(to_char(to_date('&&end_date'), 'yyyy'))
  4                       -to_number(to_char(to_date('&&start_date'), 'yyyy')) ) + 1
  5  /
Enter value for start_date: 01-jan-1900
old   1: select add_months(to_date('&&start_date'), (level-1)*12) as year
new   1: select add_months(to_date('01-jan-1900'), (level-1)*12) as year
Enter value for end_date: 01-jan-2000
old   3: connect by level <= ( to_number(to_char(to_date('&&end_date'), 'yyyy'))
new   3: connect by level <= ( to_number(to_char(to_date('01-jan-2000'), 'yyyy'))
old   4:                      -to_number(to_char(to_date('&&start_date'), 'yyyy')) ) - 1
new   4:                      -to_number(to_char(to_date('01-jan-1900'), 'yyyy')) ) - 1


YEAR
----
1900
1901
1902
...
1998
1999
2000

101 rows selected.

SQL> 
+6

Source: https://habr.com/ru/post/1737283/


All Articles