如何在一年中查询GROUP BY月份

Ray*_*ong 41 sql oracle

我正在使用Oracle SQL Developer.我基本上有一个包含列的图片表:

[DATE_CREATED(日期),NUM_of_PICTURES(int)]

如果我选择*,我会得到类似于的输出:

01-May-12    12
02-May-12    15
03-May-12    09
...
...
01-Jun-12    20
...
etc.
Run Code Online (Sandbox Code Playgroud)

我试图将这些图片总和合并为每月数字而不是每日数字.

我尝试过这样的事情:

select Month(DATE_CREATED), sum(Num_of_Pictures))
from pictures_table
group by Month(DATE_CREATED);
Run Code Online (Sandbox Code Playgroud)

这会输出错误:

ORA-00904: "MONTH": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:    
*Action:
Error at Line: 5 Column: 9
Run Code Online (Sandbox Code Playgroud)

我有月份功能错了吗?

Gor*_*off 83

我倾向于在输出中包括年份.单程:

select to_char(DATE_CREATED, 'YYYY-MM'), sum(Num_of_Pictures)
from pictures_table
group by to_char(DATE_CREATED, 'YYYY-MM')
order by 1
Run Code Online (Sandbox Code Playgroud)

另一种方式(更标准的SQL):

select extract(year from date_created) as yr, extract(month from date_created) as mon,
       sum(Num_of_Pictures)
from pictures_table
group by extract(year from date_created), extract(month from date_created)
order by yr, mon;
Run Code Online (Sandbox Code Playgroud)

请记住订单,因为您可能希望按顺序排序,并且无法保证在分组后返回行的顺序.

  • 1和2指的是要排序的列,第一列和第二列.你也可以说"yr,mon". (3认同)

Hol*_*ndt 13

对于Oracle:

select EXTRACT(month from DATE_CREATED), sum(Num_of_Pictures)
from pictures_table
group by EXTRACT(month from DATE_CREATED);
Run Code Online (Sandbox Code Playgroud)