MySQL Query to group by date range?

眉间皱痕 提交于 2019-12-22 03:52:35

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/18194950/mysql-query-to-group-by-date-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!