Skip to content
Advertisement

Is there a flexible way to specify ranges of dates?

I am working with MySQL.

I have some queries that begin like this:

I also sometimes need to run the same query, but with each date range being a week (Monday to Sunday), or a calendar month. Moreover, sometimes there are 100 or more of these, which is quite prone to typos in addition to occupying a lot of lines and taking a long time to write.

Is there more elegant and flexible way to achieve this ? Ideally I would like to be able to just specify a overall start date, an overall end date and a period (daily, weekly, monthly, yearly etc)

Advertisement

Answer

You can use a recursive CTE:

Here is a db<>fiddle. Of course, the logic would be a little different for months.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement