How to format and sort a date in Oracle?

2020-08-09 11:00发布

In my application am trying to format and sort the date, i am using to_char() function to format the date to my required format, but when i sort them it is sorting it as string sorting. But i want them to be sorted as date.

I need some help to achieve both in the same query. Kindly help me on the same.

The query which i used was,

SELECT to_char( t1.your_date_column1, your_format_mask ) as alias,
  FROM your_table1 t1,your_table2
 ORDER BY t1.your_date_column1

标签: oracle
7条回答
来,给爷笑一个
2楼-- · 2020-08-09 11:41

I wanted to Group By and Order By the Date field but the Date field included the Time and I didn't want to include the Time in the grouping and sorting. So I converted the Date to Character and then converted the character back to Date to eliminate the Time and sort by date not by text. That grouped the data by the date and sorted by the date.

-- Projects initiated by Day.
select to_date(to_char(psd.PROJECTSTATUSDATE, 'mm/dd/yyyy'),'mm/dd/yyyy') as "Date", count(*)
from project pj, project_status_date psd
where PJ.PROJECTTOKEN = PSD.PROJECTTOKEN
      and psd.PROJECTSTATUSDATE > '01-JAN-2001'
      and PSD.PROJECTSTATUSCODE = 'BL'
group by to_date(to_char(psd.PROJECTSTATUSDATE, 'mm/dd/yyyy'),'mm/dd/yyyy') 
order by to_date(to_char(psd.PROJECTSTATUSDATE, 'mm/dd/yyyy'),'mm/dd/yyyy') 

Date      Count
8/16/2013   102
8/19/2013   77
8/20/2013   257
8/21/2013   30
8/22/2013   173
8/23/2013   125
8/26/2013   41
8/27/2013   25
8/28/2013   14
查看更多
时光不老,我们不散
3楼-- · 2020-08-09 11:45

The easiest way is to retrieve the same field with the query again and doing sorting based upon that filed

In your example

SELECT 
         to_char( your_date_column, your_format_mask ) as formate_purpose,
         your_date_column as sorting_purpose
FROM your_table

ORDER BY your_date_column
查看更多
闹够了就滚
4楼-- · 2020-08-09 11:48
SELECT 
         to_char( your_date_column, your_format_mask ) as formate_purpose,

FROM your_table

ORDER BY to_date (formate_purpose)

Try the above code

查看更多
走好不送
5楼-- · 2020-08-09 11:48

For sqlplus, use alter session set nls_date_format to what you want the date format to be, then just use the column name in your select statement and sort order.

查看更多
霸刀☆藐视天下
6楼-- · 2020-08-09 11:51

You don't say what your application is written in, but in some environments (e.g. Oracle APEX, Oracle Reports) the solution is to not use to_char in the query, but then to apply the desired formatting in the tool's "column properties" or similar.

查看更多
神经病院院长
7楼-- · 2020-08-09 11:55

If you let Oracle sort (recommended), just do it like described in Justin Cave's answer. If, for some reason, you do the sorting in Java, do not use to_char; get the dates as Date objects instead and use e.g. a SimpleDateFormat to do the formatting in Java (after sorting).

查看更多
登录 后发表回答