简体   繁体   中英

Oracle date / order by question

I want to select a date from oracle table formatted like select (to_char(req_date,'MM/YYYY')) but I also want to order the result set on this date format.

I want them to be ordered like dates not strings.

Like this

09/2009
10/2009
11/2009
12/2009
01/2010
02/2010
03/2010
04/2010
05/2010
06/2010
07/2010
08/2010
09/2010
10/2010
11/2010
12/2010

Not like

01/2010
02/2010
03/2010
04/2010
05/2010
06/2010
07/2010
08/2010
09/2009
09/2010
10/2009
10/2010
11/2009
11/2010
12/2009
12/2010

Any way to do this in sql?

Full SQL is:

SELECT (to_char(req_date,'MM/YYYY')) as monthYear, count(req_id) as count
FROM   REQUISITION_CURRENT t
GROUP BY to_char(req_date,'MM/YYYY')

Thanks

Try this. It works and it's efficient, but looks a little messy.

select to_char(trunc(req_date, 'MM'),'MM/YYYY') as monthYear
      ,count(req_id) as count
  from requisition_current
 group 
    by trunc(req_date, 'MM')
 order
    by trunc(req_date, 'MM');

Please try

Select req_date, (to_char(req_date,'MM/YYYY')) from MY_TABLE order by req_date

You are free to add additional sort fields, even if they are the same field.

Try this

select monthyear,yr,month,count(req_id)
from
(
SELECT (to_char(req_date,'MM/YYYY')) as monthYear, to_char(req_date,'YYYY') yr, to_char(req_date,'mm') month, req_id
FROM   REQUISITION_CURRENT t
) x
GROUP BY monthyear,yr,month
order by yr, month

I am considerably late to the party, but the most intuitive way I've found to achieve this is the following:

SELECT DISTINCT
   to_char(req_date,'MM/YYYY') as monthYear, 
   count(req_id) as count
FROM   
   REQUISITION_CURRENT t
GROUP BY 
   to_char(req_date,'MM/YYYY')
ORDER BY 
   to_date(monthYear,'MM/YYYY')

It's may not the most computationally efficient method since it converts the date to a character and then back to a date, but that is precisely what you are asking a query like this to do. It also saves you from adding support columns or nesting subqueries.

只需使用order by req_date而不是order by to_char(req_date,'MM/YYYY')

Try

SELECT ... 
ORDER BY MIN(req_date)

That'll get around Oracle's rules about what can be selected after a GROUP BY.

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