Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all the months using oracle sql

Tags:

sql

oracle

Guys, is there any better way to list all the months other than this:

select to_char(add_months(to_date('01/01/1000', 'DD/MM/RRRR'), ind.l-1), 'MONTH') as month_descr,
       ind.l as month_ind
  from dual descr,
       (select l
          from (select level l 
                  from dual 
                connect by level <= 12
               )
       ) ind
order by 2;

ANSWER:

SELECT to_char(add_months(SYSDATE, (LEVEL-1 )),'MONTH') as months 
  FROM dual 
CONNECT BY LEVEL <= 1

ONE MORE QUESTION SEE BELOW

Also I want to list the previous two years including the current year. I wrote this sql query. Let me know if there is anything better.

select extract(year from sysdate) - (level-1) as years 
  from dual 
connect by level <=3 
order by years
like image 556
Dead Programmer Avatar asked Jan 03 '11 07:01

Dead Programmer


People also ask

How do you print all dates of particular month in a table in Oracle?

The key in this query is TRUNC(SYSDATE, 'MONTH') which is the first day of the current month. We use hierarchical queries to keep adding one day to the first day of the month until the value is no longer in the current month. We use LEVEL - 1 because LEVEL starts from 1 and we need it to start from zero.

How do I display months between two dates in SQL?

Example: Oracle MONTHS_BETWEEN () function The following statement calculates the months between two specified dates: SQL> SELECT MONTHS_BETWEEN 2 (TO_DATE('02-02-2015','MM-DD-YYYY'), 3 TO_DATE('12-01-2014','MM-DD-YYYY') ) "Months" 4 FROM DUAL;.

What does Add_months do in Oracle?

ADD_MONTHS returns the date date plus integer months. A month is defined by the session parameter NLS_CALENDAR . The date argument can be a datetime value or any value that can be implicitly converted to DATE . The integer argument can be an integer or any value that can be implicitly converted to an integer.


2 Answers

Not better, but just a bit cleaner:

SQL>  select to_char(date '2000-12-01' + numtoyminterval(level,'month'),'MONTH') as month
  2     from dual
  3  connect by level <= 12
  4  /

MONTH
---------
JANUARY
FEBRUARY
MARCH
APRIL
MAY
JUNE
JULY
AUGUST
SEPTEMBER
OCTOBER
NOVEMBER
DECEMBER

12 rows selected.

Regards, Rob.

like image 186
Rob van Wijk Avatar answered Sep 28 '22 07:09

Rob van Wijk


Yup.

1:

SELECT * FROM WWV_FLOW_MONTHS_MONTH;

2: (UPD:)

WITH MONTH_COUNTER AS (
  SELECT LEVEL-1 AS ID 
  FROM DUAL 
  CONNECT BY LEVEL <= 12
) 
SELECT TO_CHAR(ADD_MONTHS(TO_DATE('01/01/1000', 'DD/MM/RRRR'), ID),'MONTH') FROM MONTH_COUNTER;
like image 33
ksogor Avatar answered Sep 28 '22 05:09

ksogor