Oracle按年,月排序

时间:2014-04-10 09:52:57

标签: sql oracle sql-order-by

我有一个查询,我想按年份和月份订购。我通过to_date(depdate,'mm')和TO_CHAR(depdate,'YYYY / MM')尝试了命令。这是我正在查询的表的一个sqlfiddle和查询本身sqlfiddle

2 个答案:

答案 0 :(得分:4)

您希望按date值排序,而不是按字符串表示排序。这意味着您还希望group by date值。 trunc(<<date column>>, 'mm')会在本月的第一天将date截断为午夜。像这样的东西

SELECT to_char(trunc(DEPDATE,'MM'), 'Mon-YYYY') AS MONTH, 
       SUM(AMOUNTROOM) AS ROOMTOTAL, 
       SUM(AMOUNTEXTRAS) AS EXTRATOTAL, 
       SUM(AMOUNTEXTRAS + AMOUNTROOM) AS OATOTAL 
FROM checkins 
WHERE checkinstatus = 'D' AND depdate > TO_DATE('2013-12-01', 'yyyy/mm/dd') 
  AND depdate <= TO_DATE('2014-04-10', 'yyyy/mm/dd')
GROUP BY trunc(depdate,'mm')
ORDER BY trunc(depdate,'mm');

应该是您正在寻找的。见the updated fiddle

答案 1 :(得分:1)

查看此查询。如果它是一个日期字段,那么只需按顺序排列即可。您不需要使用TO_CHAR转换为字符串然后排序:

WITH TAB AS
(
 SELECT SYSDATE  DATEVAL FROM DUAL
 UNION
 SELECT SYSDATE + 100 DATEVAL FROM DUAL
 UNION
 SELECT SYSDATE -500 DATEVAL FROM DUAL
 UNION
 SELECT SYSDATE + 30 DATEVAL FROM DUAL
 UNION
 SELECT SYSDATE -30 DATEVAL FROM DUAL
) SELECT * FROM TAB
ORDER BY DATEVAL DESC