Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Query to group by date range?

I've got a table in MySQL that shows me number of hours logged on a daily basis. I'm trying to build a view that will allow me to quickly group my data by blocks/range of days. The simplest case would be on a monthly basis which wouldn't be difficult. I could just select the date as "%y-%m" and then group by that column.

Ex:

select time_logged, date_format(start_date, '%Y-%m') AS `month_logged`
from work_log
group by month_logged

That works fine if I am just grouping by month. But my issue is that I need to group from the 13th of the month to the 12th of the following month (ex: July 13-Aug 12, Aug 13- Sept 12, etc).

Is there an easy way to do something like that in a single query/view? I can't seem to come up with a query that works for my needs, even playing with the different date field combinations.

like image 750
Eric B. Avatar asked Aug 12 '13 19:08

Eric B.


1 Answers

Subtract 13 days and do the grouping you are doing now:

select time_logged,
       date_format(start_date - interval 12 day, '%Y-%m') AS `month_logged`
from work_log
group by month_logged;
like image 158
Gordon Linoff Avatar answered Sep 23 '22 16:09

Gordon Linoff