简体   繁体   中英

How to extract month number from date in Oracle

I have ID_BB_SECURITY column where the date value is stored in this column for example '20190801' .

I want to get month number from this field for example for August date i want to get 8.

I tried below query but it throws an error 'literal does not match':

select to_number(to_date(ID_BB_SECURITY),'mm') from BT_EXPORT

I am not sure if i have to ignore null values so as to avoid the error

If the value is a number or string then you can convert it to a date with an appropriate mask - which is what you are missing, and what is causing the error you are getting (as it's using your session's NLS_DATE_FORMAT setting, which apparently does not match the format of the data; but which you should not rely on anyway, as @MTO said in comments):

to_date(ID_BB_SECURITY, 'YYYYMMDD')

and then extract the month number from that:

select extract(month from to_date(ID_BB_SECURITY, 'YYYYMMDD')) from BT_EXPORT

Or you could just use a substring:

select to_number(substr(ID_BB_SECURITY, 5, 2)) from BT_EXPORT;

Those assume a fixed consistent format, which is always a risky assumption when using the wrong data type. Ans if it's a number they are doing an implicit conversion from number to string, which you could turn into an explicit conversion for greater clarity.

If it's already a date - as it should be, of course - then you don't need the conversion:

select extract(month from ID_BB_SECURITY) from BT_EXPORT

If you have a number, you can use arithmetic to extract the month:

select mod(floor(20190801 / 100), 100)
from dual;

You could try converting the number date to a string, and then extracting the 5th and 6th characters:

SELECT
    SUBSTR(TO_CHAR(ID_BB_SECURITY), 5, 2) AS mm
FROM BT_EXPORT;

But, it would be much better for you to use a proper date column. Then, you could use a less draconian method such as:

SELECT
    TO_CHAR(ID_BB_SECURITY, 'mm') AS mm  -- assuming date
FROM BT_EXPORT;
select to_number(to_char(to_date('20190801', 'yyyymmdd'), 'mm')) from dual

select extract(month from to_date('20190801', 'yyyymmdd')) from dual

Try this one

select extract(month from to_date(ID_BB_SECURITY, 'YYYYMMDD')) from BT_EXPORT

This one convert number to date then extract month.

Your date column has the value stored in the following format "yyyymmdd" where

  • yyyy is the year
  • mm the month
  • dd the day So in order to return the number value of the month (mm) we can do as follows:

    1: first transform the value from a number to a date using to_date(20190801,'yyyymmdd')

    2: get month using to_date operator to_char( to_date(20190801,'yyyymmdd'), 'mm')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM