Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bring back an entire range of dates in SQL between two dates, even when there is no data?

Tags:

sql

sql-server

Trying to get the number of incidents in my database, in the format:

date   numberOfIncidents
date   numberOfIncidents
date   numberOfIncidents
date   numberOfIncidents

I supply the start date / end date to my SQL stored procedure, but if there is no entry in the database for a particular date (because no incidents occured) then I wont get the full range back.

What I want is every single date to be returned between my start/end dates, with a value next to it.

Is this possible in SQL Server?

like image 339
NibblyPig Avatar asked Dec 12 '25 00:12

NibblyPig


1 Answers

You can use a recursive common table expression to produce the date range and then join it to your incidents.

WITH DateRange(date) AS
(
  SELECT @dateFrom date
  UNION ALL
  SELECT DATEADD(dd, 1, date) date FROM DateRange WHERE date < @dateTo
)

SELECT DateRange.date, count(incident.id) 
FROM DateRange
LEFT OUTER JOIN incident
  ON incident.date >= DateRange.date 
  AND incident.date < DATEADD(dd, 1, DateRange.date)
GROUP BY DateRange.date
ORDER BY DateRange.date

By default, SQL Server limits the recursive definition to 100 rows. If you need more than 100 date rows, append OPTION (MAXRECURSION n) to the end of the query, changing n to the required number of rows.

like image 163
Phil Ross Avatar answered Dec 13 '25 13:12

Phil Ross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!