Oracle按月,按年,按年,按月分组

时间:2017-12-18 20:15:25

标签: oracle group-by sql-order-by

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

我目前的查询是:

#123

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

所以我想修复一下,我会稍微调整一下查询:

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;

2 个答案:

答案 0 :(得分:1)

只需将extract(month from datumgeleend)添加到group by子句:

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;

答案 1 :(得分:0)

一个简单的解决方法,使用WITH factoring子句,附加列(必须包含在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;