我正在使用 Oracle SQL Developer。 我基本上有一个包含列的图片表格:
[DATE_CREATED(日期),NUM_of_PICTURES(整数)]
如果我执行 select *,我会得到类似于以下内容的输出:
01-May-12 12
02-May-12 15
03-May-12 09
...
...
01-Jun-12 20
...
etc.
我正在尝试将这些图片总数汇总为每月数字而不是每日数字。
我尝试过这样做:
select Month(DATE_CREATED), sum(Num_of_Pictures))
from pictures_table
group by Month(DATE_CREATED);
这会输出一个错误:
ORA-00904: "MONTH": invalid identifier
00904. 00000 - "%s: invalid identifier"
*Cause:
*Action:
Error at Line: 5 Column: 9
我的月份函数有错吗?
最佳答案
我倾向于在输出中包含年份。一种方法:
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
另一种方式(更标准的 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;
记住 order by,因为您可能希望这些按顺序排列,并且不能保证在 group by 之后返回行的顺序。
关于sql - 如何查询GROUP BY一年中的月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11531785/