简体   繁体   中英

How to convert Varchar into Date

I'm trying to create a Trial Balance Report ,

and i have a field named : 'PERIOD_NAME' which stores the accounting period name,

and my question is : is it possible to convert the 'PERIOD_NAME' which is a "VARCHAR2" into "DATE" in order to sort the months ASC , To give me this Result

jan- 16
jan- 17
Feb- 16
Feb- 17

Use TO_DATE( string, format_model, nls_settings ) assuming your PERIOD_NAME is like jan-17 (but it is unclear from your question what the exact format is):

SELECT TO_DATE( period_name, 'MON-YY', 'NLS_DATE_LANGUAGE=English' )
FROM   your_table;

If you want to sort by month then year then you can use EXTRACT to get the month or year and sort on that:

SELECT *
FROM   (
  SELECT TO_DATE( period_name, 'MON-YY', 'NLS_DATE_LANGUAGE=English' ) AS period_date
  FROM   your_table
)
ORDER BY EXTRACT( MONTH FROM period_date ),
         EXTRACT( YEAR FROM period_date );

I think this is what you are after? Basically, I have used to_date to convert the period name to a date and then extracted the month and year separately to use in the sort. Hope this helps!

Data

CREATE TABLE my_table 
(
  col1 VARCHAR2(10)
)  ;
INSERT INTO my_table VALUES ('jan- 16');
INSERT INTO my_table VALUES ('jan- 17');
INSERT INTO my_table VALUES ('Feb- 16');
INSERT INTO my_table VALUES ('Feb- 17');

Solution

SELECT t.*
  FROM my_table t
 ORDER BY to_char(to_date(col1, 'mon- yy'), 'mm'),
          to_char(to_date(col1, 'mon- yy'), 'yy')

Result

COL1

jan- 16

jan- 17

Feb- 16

Feb- 17

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