KatInterview

Staggered-Rollout Panel and Weekly Rollup in SQL

SQL & DataModel answer
MediumModel answerSQL & Datasqldifference-in-differencespanel-data

Last updated

Write warehouse SQL that turns daily participation logs into a treatment-aware employee-day panel and a site-week participation table for a staggered-rollout DiD analysis.

Context

A company launched a commuter shuttle at some of its office sites on different dates. Analysts want to measure whether the shuttle raised office participation, using a staggered-adoption difference-in-differences design. Sites that never got the shuttle act as controls.

Schema

sites(site_id, city)
employees(employee_id, site_id, hire_date)
shuttle_service(site_id, start_date)      -- rows exist only for sites that got the shuttle
participation(employee_id, date, participated)

Sample data:

site_idcity
1SEA
2NYC
employee_idsite_idhire_date
10112024-10-01
10212025-01-01
20122024-11-15
site_idstart_date
12025-01-15
employee_iddateparticipated
1012025-01-101
1012025-01-201
1022025-01-200
2012025-01-101
2012025-01-200

Task

Write SQL (PostgreSQL or BigQuery) that produces two outputs.

1. Employee-day panel with columns:

  • employee_id, site_id, date, participated
  • adoption_date: the site's shuttle start date, or NULL if the site never had one
  • treated_site: 1 if date >= adoption_date at that site, otherwise 0. Never-treated sites always get 0.
  • event_time_days: date - adoption_date in days, NULL for never-treated sites
  • post: a binary after-adoption indicator

2. Weekly site-level table with participation_rate = AVG(participated) for every site-week. Sites without a shuttle must be included and handled correctly.

Rules

  • Be careful with the adoption boundary so there are no off-by-one errors.
  • Employees never change sites, so the site in employees is valid for every day.

What to deliver

The SQL, the reasoning behind your join and boundary choices, and the output it should give on the sample data.

Hints

Hint 1

Start by reducing shuttle_service to a single adoption date per site, then decide which join type keeps sites that have no shuttle row.

Hint 2

Define the rule date >= adoption_date once and derive treated_site, post and event_time_days from it, so the columns cannot disagree. Check that both sides are DATE types, not timestamps.

Hint 3

Build the weekly table by grouping the finished employee-day panel rather than the raw tables. Think about what to do with the week that contains the adoption date, since it is part pre and part post.