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');
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
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.
Just use order by req_date
instead of 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.
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.
精彩评论