Oracle 按月、年、按年、月排序

Oracle Group By Month, Year, Order by Year, Month

我正在尝试在 Oracle 中编写一个查询,该查询将按月和年对日期进行分组,然后将它们整齐地排序。 除此之外,月份必须显示其名称而不是月份编号。

我目前的查询是:

SELECT to_char(datumgeleend, 'MONTH') as "Maand geleend", 
to_char(datumgeleend, 'YYYY') as "Jaar geleend", SUM(bedrag)
FROM lening
GROUP BY to_char(datumgeleend, 'MONTH'), to_char(datumgeleend, 'YYYY')
ORDER BY to_char(datumgeleend, 'YYYY'), to_char(datumgeleend, 'MONTH') DESC;

问题是按月份的第一个字母而不是月份的数字排序。

所以我想解决这个问题,我将查询稍微调整为:

SELECT to_char(datumgeleend, 'MONTH') as "Maand geleend", 
to_char(datumgeleend, 'YYYY') as "Jaar geleend", SUM(bedrag)
FROM lening
GROUP BY to_char(datumgeleend, 'MONTH'), to_char(datumgeleend, 'YYYY')
ORDER BY to_char(datumgeleend, 'YYYY'), extract(month from datumgeleend) 
DESC;

遗憾的是,此查询生成以下错误:

ORA-00979: not a GROUP BY expression

一个简单的解决方法,使用 WITH 分解子句,附加列(必须包含在 GROUP BY 子句中)用于根据需要对数据进行排序:

WITH temp AS (
  SELECT
    TO_CHAR(datumgeleend,'MONTH') AS maand_geleend,
    TO_CHAR(datumgeleend,'YYYY') AS jaar_geleend,
    SUM(bedrag) sum_bedrag,
   --
    TO_CHAR(datumgeleend,'yyyymm') yyyymm
  FROM
    lening
  GROUP BY
    TO_CHAR(datumgeleend,'MONTH'),
    TO_CHAR(datumgeleend,'YYYY'),
    TO_CHAR(datumgeleend,'yyyymm')
) SELECT
  maand_geleend,
  jaar_geleend,
  sum_bedrag
  FROM
  temp
ORDER BY
  yyyymm DESC;

只需将 extract(month from datumgeleend) 添加到分组中:

SELECT to_char(datumgeleend, 'MONTH') as "Maand geleend", 
to_char(datumgeleend, 'YYYY') as "Jaar geleend", SUM(bedrag)
FROM lening
GROUP BY to_char(datumgeleend, 'MONTH'), to_char(datumgeleend, 'YYYY'), extract(month from datumgeleend)
ORDER BY to_char(datumgeleend, 'YYYY'), extract(month from datumgeleend) DESC;