Oracle date to_char group and order by

时间:2017-05-26 09:20:15

标签: mysql oracle

我正在努力将我的查询从mysql迁移到oracle。在mysql中我使用查询只获得月份

SELECT DATE_FORMAT(IDATEIN, '%M-%Y') as MY 
  FROM ATTENDANCE 
 GROUP BY MY 
 ORDER BY IDATEIN DESC

给我的结果如

MYDATE
DEC-2016
NOV-2016
OCT-2016

我的表格包含

IDATEIN
2016-12-01
2016-12-01
2016-12-01
2016-10-01
2016-11-01

在oracle中我试图使用这个

  SELECT TO_CHAR(DATEIN, 'MON-YYYY') AS MY 
    FROM HRM_ATTENDANCE 
   GROUP BY TO_CHAR(DATEIN, 'MON-YYYY') 
   ORDER BY TO_CHAR(DATEIN, 'MON-YYYY')

但它订购了abphables,比如

 APR-2016
 APR-2017
 AUG-2016
 FEB-2016
 FEB-2017

请帮忙

Oracle结果

Oracle Result

Mysql结果

Mysql Result

1 个答案:

答案 0 :(得分:2)

使用TRUNC将日期截断到月初,并GROUP BY / ORDER BY该日期值,并将其转换为SELECT子句中的字符串:

SELECT   TO_CHAR( TRUNC( DATEIN, 'MM' ), 'MON-YYYY') AS MY 
FROM     HRM_ATTENDANCE 
GROUP BY TRUNC( DATEIN, 'MM' ) 
ORDER BY TRUNC( DATEIN, 'MM' )

但是,由于您的数据似乎只是本月的第一天,因此可以简化为:

SELECT   TO_CHAR( DATEIN, 'MON-YYYY') AS MY 
FROM     HRM_ATTENDANCE 
GROUP BY DATEIN 
ORDER BY DATEIN