Home > Database > Mysql Tutorial > How to Fill Missing Dates with Zero Values in SQL Queries?

How to Fill Missing Dates with Zero Values in SQL Queries?

Mary-Kate Olsen
Release: 2024-12-17 11:08:25
Original
416 people have browsed it

How to Fill Missing Dates with Zero Values in SQL Queries?

Retrieve Missing Dates with Zero Values between Date Ranges

The original query retrieved data between two dates, but it excluded missing dates. To include missing dates and assign a zero value for the missing data, we can utilize a technique called "date flagging."

Flagging Missing Dates

A recursive common table expression (CTE) can be used to generate a series of dates within the specified range. The CTE, named d, starts with the first date of the range and recursively adds one day until it reaches the end date.

;with d(date) as (
  select cast('10/01/2012' as datetime)
  union all
  select date+1
  from d
  where date < '10/15/2012'
  )
Copy after login

Joining with Existing Data

Next, we perform a left outer join between the CTE d and the original data table temp (t) to retrieve the existing data for each date. If a date exists in temp, the value is used; otherwise, we substitute zero.

select t.ID, d.date CDate, isnull(t.val, 0) val
from d
left join temp t
       on t.CDate = d.date
order by d.date
OPTION (MAXRECURSION 0) -- use this if your dates are >99 days apart
Copy after login

Note on MAXRECURSION

The OPTION (MAXRECURSION 0) clause prevents the query from failing due to excessive recursion if the date range is too large. You can adjust the value to suit your specific data range.

By using this technique, we can retrieve all dates between two dates, including missing dates, while ensuring that the missing values are represented as zero.

The above is the detailed content of How to Fill Missing Dates with Zero Values in SQL Queries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template