Interview Questions/SQL/Date Series Gap-Fill with Event Counts

Date Series Gap-Fill with Event Counts

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given an Events table and a DateRange table with a single row containing a start and end date. Write a SQL query that generates every calendar date in [start_date, end_date] using a recursive CTE, and for each date reports the total event count, click count, and view count - even for dates with no events (showing 0s). Return (event_date, total_events, clicks, views) ordered by event_date. Table: Events

Column NameTypeDescription
event_idINTPrimary key
event_dateDATEDate of the event
event_typeVARCHAREither 'click' or 'view'

Table: DateRange

Column NameTypeDescription
start_dateDATERange start
end_dateDATERange end

Database Schema (Inferred)

Events

Column NameExample Value
event_id1
event_date2024-01-01
event_typeclick

DateRange

Column NameExample Value
start_date2024-01-01
end_date2024-01-07

Example

Events

event_idevent_dateevent_type
12024-01-01click
22024-01-01click
32024-01-03view
42024-01-05click
52024-01-05view
62024-01-05click

DateRange

start_dateend_date
2024-01-012024-01-07

Output

event_datetotal_eventsclicksviews
2024-01-01220
2024-01-02000
2024-01-03101
2024-01-04000
2024-01-05321
2024-01-06000
2024-01-07000

Explanation:

Generate the full date range with a recursive CTE. LEFT JOIN events to preserve gap dates. Use conditional aggregation to split clicks vs views.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Events

event_idevent_dateevent_type
12024-01-01click
22024-01-01click
32024-01-03view
42024-01-05click
52024-01-05view
62024-01-05click

DateRange

start_dateend_date
2024-01-012024-01-07

Output

event_datetotal_eventsclicksviews
2024-01-01220
2024-01-02000
2024-01-03101
2024-01-04000
2024-01-05321
2024-01-06000
2024-01-07000