Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query GROUP BY Month in a Year

Tags:

sql

oracle

People also ask

Can we group by month in SQL?

Group By Month and Year We also use YEAR() and MONTH() functions to ensure that data is grouped and ordered by month and year numbers. In the above query, if we use date_format function in group by clause, then MySQL will sort the groups alphabetically, instead of chronologically.

How do I Group A timestamp by month?

You can group month and year with the help of function DATE_FORMAT() in MySQL. The GROUP BY clause is also used.

How do I select data by month in SQL?

To select all entries from a particular month in MySQL, use the monthname() or month() function.


I would be inclined to include the year in the output. One way:

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

Another way (more standard 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;

Remember the order by, since you presumably want these in order, and there is no guarantee about the order that rows are returned in after a group by.


For Oracle:

select EXTRACT(month from DATE_CREATED), sum(Num_of_Pictures)
from pictures_table
group by EXTRACT(month from DATE_CREATED);