我有一个存储过程,select语句是:
SELECT COUNT(IDENTIFIER) AS TOTALORDER,SUM(FT.ACTUALORDER01+FT.ACTUALORDER02+FT.ACTUALORDER03+FT.ACTUALOR DER04) AS TOTALORDER,
SUM(TOTALPENDING) AS PENDING,
TO_CHAR(TO_DATE(DATE),'MonthYYYY') AS "Month-Year"
FROM FTORDER FT FULL JOIN FSDPENDING FS
ON FS.IDENTIFIER=FT.ORDERNUMBER
AND FT.ORDERDATE=FS.ORDERDATETIME
AND FT.ORDREcode=FS.ORDERcode
AND FT.sequence=FS.sequence
AND FT.recordstatus=FS.recordstatus
WHERE TRUNC(FORDERDATETIME) BETWEEN TO_DATE('01-JAN-2014','dd/mon/yyyy') AND TO_DATE('31-DEC-2015','dd/mon/yyyy')
AND TORDERNUMBER NOT LIKE ('-%')
GROUP BY TO_CHAR(TO_DATE(DATE),'MonthYYYY')
ORDER BY "Month-Year"
;
这显示了每个月的总和但是我需要按月和年订购结果,因为我的结果显示如下:
April 2013
February 2013
January 2013
June 2013
March 2013
May 2013
在这种情况下解决方案是什么?
答案 0 :(得分:2)
将to_date的格式更改为(YYYY-MM),然后按此顺序(DESC或ASC)按顺序获取它。目前,它是根据月份名称按字母顺序排序。
答案 1 :(得分:2)
TO_CHAR(TO_DATE(DATE), 'MonthYYYY')
有些事情不正确。
永远不要在 DATE 列上应用 TO_DATE 。它迫使Oracle:
基于区域设置特定的NLS设置。您需要 TO_DATE 才能将文字转换为日期。对于日期算术,请保留日期。
您目前正在对字符串进行排序,因为 TO_CHAR 会将日期转换为字符串。
你可以这样做:
SQL> alter session set nls_date_format = 'YYYY-MON-DD';
Session altered.
SQL> SELECT TRUNC(hiredate,'MONTH')
2 FROM emp
3 GROUP BY TRUNC(hiredate,'MONTH')
4 ORDER BY TRUNC(hiredate,'MONTH');
TRUNC(HIRED
-----------
1980-DEC-01
1981-FEB-01
1981-APR-01
1981-MAY-01
1981-JUN-01
1981-SEP-01
1981-NOV-01
1981-DEC-01
1982-JAN-01
1982-DEC-01
1983-JAN-01
11 rows selected.
注意:alter session语句仅以所需格式显示日期。