Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Rolling 30-Day Event Counts
00:00
5 left

Rolling 30-Day Event Counts

HardSQL · PostgreSQL

Problem

Write a SQL query using window functions to calculate each patient's rolling 30-day event count and rank the most recent events.

Return one row for every recorded event. The rolling count includes the event itself and other events for the same patient from the preceding 30 days through the event timestamp. Rank events separately for each patient by event timestamp descending, allowing events at the same timestamp to share a rank.

Output

  1. Return patient_id, patient_name, event_id, event_timestamp, event_type_name, rolling_30_day_event_count, and recency_rank.
  2. Sort by patient_id, recency_rank, then event_id.

Schema

patients
ColumnTypeDescription
patient_idPKINTUnique patient identifier
patient_nameVARCHAR(100)Patient display name
date_of_birthDATEPatient date of birth
patient_events
ColumnTypeDescription
event_idPKINTUnique event identifier
patient_idINTPatient associated with the event
event_timestampTIMESTAMPTimestamp when the event occurred
event_type_idINTOptional event type identifier
event_types
ColumnTypeDescription
event_type_idPKINTUnique event type identifier
event_type_nameVARCHAR(100)Human-readable event type
Tablespatientspatient_eventsevent_types
Interviewer

Your question is Rolling 30-Day Event Counts. Start with the requirements and the three tables in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePostgreSQL
You need to log in / sign up to run or submit.Ln 1
Run your query to see results here.