Skip to content
Advertisement

How to determine the number of days in a month for a given Date Range?

I need to calculate using SQL Query, how many days within a given range fall into each calendar month.

I have given 2 dates, which define a date range; for example 2020-01-01 to 2020-08-03. I need to find how many days in that range fall in to each month i.e. how many fall into July, and how many into August.

In the example given, the expected result is 31 days in July and 3 days in August.

Advertisement

Answer

One approach uses a recusive query. Using date artithmetics, we can build the query so it performs one iteration per month rather than one per day, so this should be a rather efficient approach:

Demo on DB Fiddle.

If we set the boundaries as follows:

Then the query returns:

month_start | no_days
:---------- | ------:
2020-07-01  |      22
2020-08-01  |      31
2020-09-01  |      10
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement