how to convert date into month number?

2019-02-27 15:38发布

I have a column Month in my table. The month name and date are stored in this month column like

Month    
01-JAN-12 
02-FEB-12 

and so on.

How do I convert the DATE into month number such as

Month
1 
2 

etc.

7条回答
地球回转人心会变
2楼-- · 2019-02-27 15:46
        SELECT  ( CASE yourDate
        WHEN 'Jan' THEN 1
        WHEN 'Feb' THEN 2
        WHEN 'Mar' THEN 3
        WHEN 'Apr' THEN 4
        WHEN 'May' THEN 5
        WHEN 'Jun' THEN 6
        WHEN 'Jul' THEN 7
        WHEN 'Aug' THEN 8
        WHEN 'Sep' THEN 9
        WHEN 'Oct' THEN 10
        WHEN 'Nov' THEN 11
        WHEN 'Dec' THEN 12
       END )
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-02-27 15:55

datepart function do this easily

SELECT DATEPART(m, getdate()) 
查看更多
贪生不怕死
5楼-- · 2019-02-27 16:04
select 
to_char(to_date('01-JAN-12','dd-mon-yy'),'mm') from dual;
查看更多
ら.Afraid
6楼-- · 2019-02-27 16:07

Extract works perfectly for this

EXTRACT extracts and returns the value of a specified datetime field

with fullYear as(
  select (to_date('01-jan-12') + 29*level) dte
    from dual
  connect by level <= 12
  )

select extract(month from dte) month, dte from fullYear ;

gives you

MONTH       DTE
1           January, 30 2012 00:00:00+0000
2           February, 28 2012 00:00:00+0000
3           March, 28 2012 00:00:00+0000
4           April, 26 2012 00:00:00+0000
5           May, 25 2012 00:00:00+0000
6           June, 23 2012 00:00:00+0000
7           July, 22 2012 00:00:00+0000
8           August, 20 2012 00:00:00+0000
9           September, 18 2012 00:00:00+0000
10          October, 17 2012 00:00:00+0000
11          November, 15 2012 00:00:00+0000
12          December, 14 2012 00:00:00+0000
查看更多
聊天终结者
7楼-- · 2019-02-27 16:07

Totally agree regarding writing a case when Oracle offers built-in functionality:

SELECT EXTRACT(MONTH FROM DATE '2012-03-15') FROM DUAL;

SELECT EXTRACT(MONTH FROM TO_DATE('01-JAN-12', 'DD-MON-RR')) month_to_number FROM DUAL;

select to_number(to_char(to_date('01-JAN-12','dd-mon-yy'),'mm')) month_to_number from     dual;

select to_number(to_char(trunc(sysdate), 'mm')) month_to_number from dual;
查看更多
登录 后发表回答