在Oracle中按月分组

时间:2014-11-11 11:31:49

标签: oracle

我正试图在oracle中按月分组,但我在“YEAR”函数上获得了一个无效的标识符,不知道为什么。

这是我的代码:

SELECT CAST(MONTH(day_date) AS VARCHAR(2)) + '-' + CAST(YEAR(day_date) AS VARCHAR(4)) AS MY_DATE,
sum(cash_sales) as cash_sales, sum(unit_sales) as unit_sales
FROM NC_SALES_CAT_TL
GROUP BY CAST(MONTH(day_date) AS VARCHAR(2)) + '-' + CAST(YEAR(day_date) AS VARCHAR(4))

如何按月完成所需的分组?

1 个答案:

答案 0 :(得分:3)

Oracle中的连接运算符是||。不是+

SQL> select 'a' +' b' from dual;
select 'a' +' b' from dual
       *
ERROR at line 1:
ORA-01722: invalid number
SQL> select 'a' || 'b' from dual;

'A
--
ab

此外,YEAR是一个MySQL函数。在Oracle中,您将使用EXTRACT(YEAR FROM ....)


最后,您是否了解TO_CHAR功能?

因此,您应该将整个查询重写为:

SELECT TO_CHAR(day_date, 'MM-YYYY') AS MY_DATE,
       sum(cash_sales) as cash_sales, sum(unit_sales) as unit_sales
FROM NC_SALES_CAT_TL
GROUP BY TO_CHAR(day_date, 'MM-YYYY')