Skip to content

Merge subscription rows into continuous customer stretches

HardFull bankGaps and islandsAnalytics engineering30 min2 hidden datasets

The task

subscriptions has one row per plan period, and a plan change creates a new row. For a retention report, join the rows of each account into continuous stretches of being a customer.

A row covers the days from started_on up to, but not including, ended_on. A NULL ended_on means the row is still active, so it never ends. Two rows of the same account belong to the same stretch when the later one starts on or before the day the stretch so far ends: back-to-back rows (one starts the day the other ends) and overlapping rows both merge. A row that starts after the stretch has ended, even by one day, begins a new stretch. A row can also sit entirely inside an earlier, longer row. Order an account's rows by started_on, then subscription_id.

Return one row per stretch:

  • account_id
  • stretch_start: the earliest started_on in the stretch
  • stretch_end: the latest end of the stretch, or NULL if any row in it is still active
  • plan_rows: how many subscription rows the stretch contains

Sort by account_id, then stretch_start.

Expected output

account_idstretch_startstretch_endplan_rows
  • Sorted by account_id ascending, then stretch_start ascending.
  • Checked on the sample and on 2 hidden datasets. How grading works

Tables B2B software company · click a name to insert it

accounts110 rows in the sample

One row per customer company. Key: account_id.

intUnique id.
textCompany name.
textRetail, Finance, Education, Media, Logistics, Software or Manufacturing.
textTwo-letter country code.
dateDay the account was created.
textName of the owner on our side. NULL when unassigned.
plans4 rows in the sample

Price list. Key: plan_id.

textstarter, team, business or enterprise.
textDisplay name.
numeric(10,2)Monthly price per seat, USD.
subscriptions149 rows in the sample

One row per stretch of time an account spent on one plan. A plan change ends one row and starts another on the same day. Key: subscription_id.

intUnique id.
intThe account.
textThe plan.
intSeats paid for.
dateFirst day on this plan.
dateDay it stopped (not included). NULL while active.
invoices1,090 rows in the sample

One invoice per account per month while subscribed. Key: invoice_id.

intUnique id.
intThe account billed.
dateIssue day.
datePayment due day.
numeric(10,2)Amount billed, USD.
dateDay it was paid. NULL if unpaid.

Related questions

Loading the editor and PostgreSQL