Skip to content
Advertisement

Calculate the number of records for each date between 2 dates

I have to create a query to return results for a multi-axis chart. I need to count the number of Ids created for each date between 2 dates. I tried this:

Of course, the problem is with the ;WITH which returns the error

Operand type clash: datetime2 is incompatible with int.

The above works if I give it a specific number of days from the current date like:

Which returns:

enter image description here

The problem is that I cannot figure out how to substitute the date range.

Advertisement

Answer

No need to reinvent the wheel – there are many examples of recursive CTE calendar tables out there, similar to below.

Comments:

  • Why use a datetime2 for a date?
  • Do you definitely want < the end date or <=?
  • Are you familiar with how between works – its not always intuitive.
  • Alias all tables for better readability.
  • Semi-colon terminate all statements.
  • Consistent casing makes the query easier to read.
  • Use an unambiguous date format for date strings.
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement