Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Joins, CTEs, and Intervals

HardSQL · PostgreSQL00:00
Practice interviewer
In session
5 left
00:00

Your question is SQL Joins, CTEs, and Intervals. Start with the requirements and the three tables on the right.

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.

Problem

Sberbank wants to identify continuous customer activity periods in Sberbank Online. Activity records can be duplicated during ingestion, and separate events belong to the same interval when the next event starts no later than one day after the running end of the current interval.

Write a PostgreSQL query that joins all three tables and returns only intervals lasting at least two calendar days and containing at least two distinct Sberbank Online activity types.

Requirements

  1. Deduplicate events by customer, activity type, start date, and end date, keeping the row with the latest ingested_at.
  2. Join customers, activity events, and activity types, retaining only channel = 'Sberbank Online'.
  3. Use CTEs and window functions to merge overlapping or adjacent intervals. The chaining logic must compare each event with the running maximum end date, not only the immediately preceding event.
  4. Return the customer, merged interval boundaries, inclusive active days, distinct activity type count, and deduplicated event count.
  5. Keep intervals meeting both thresholds and order the result by customer and interval start.

Schema

customers
ColumnTypeDescription
customer_idPKINTUnique Sberbank customer identifier
customer_nameVARCHAR(100)Customer display name
activity_events
ColumnTypeDescription
event_idPKINTUnique ingested event record
customer_idINTReferences customers.customer_id
activity_type_idINTReferences activity_types.activity_type_id
start_dateDATEActivity interval start date
end_dateDATEActivity interval end date
ingested_atTIMESTAMPTimestamp when the record was ingested
activity_types
ColumnTypeDescription
activity_type_idPKINTUnique activity type identifier
activity_nameVARCHAR(80)Readable activity name
channelVARCHAR(40)Sberbank product or channel where the activity occurred
Tablescustomersactivity_eventsactivity_types
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results