简体   繁体   中英

SQL yyyymm date formatting

I have a month column in YYYYMM-Example 201204 format and I need to break it into two column year(2012) and month(04)????

I've tried using Ltrim & Rtrim to break apart but not really working.

This requires string manipulations, which differ by database. A typical method is:

select substr(col, 1, 4) as yyyy, substr(col, 5, 2) as mm

In some databases, the function would be substring() . Most databases support either substr() or substring() .

Try

select yyyy = datepart( year  , t.datetime_column ) ,
       mm   = datepart( month , t.datetime_column ) ,
       ...
from dbo.some_table t

Or

select yyyy = year(  t.datetime_column ) ,
       mm   = month( t.datetime_column ) ,
       ...
from dbo.some_table t

Or, if the column is a string:

select yyyy = convert(int, left(  t.some_column , 4 ) ) ,
       mm   = convert(int, right( t.some_column , 2 ) ) ,
       ...
from dbo.some_table t
where t.some_column like '[0-9][0-9][0-9][0-9][0-9][0-9]'

Assuming Oracle (since none is specified) and varchar/char this would be another option:

select 
    extract(year from (to_date('201204', 'yyyymm'))) year, 
    extract(month from (to_date('201204', 'yyyymm'))) month 
from dual;

First, convert to date and then get the month and year using extract function. Assumes month is always two chars and year four.

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