Unbroken runs of months

window functions

Unbroken runs of months

Shopify SQL Interview Question

Shopify counts a merchant who left and came back as two relationships rather than one, because the second behaves differently: shorter, more price sensitive, more likely to leave again. The billing history is a row per month a merchant was active, with nothing recorded for the months they were gone.

Return one row per unbroken run of active months: the merchant_id, the first month of the run as run_start, the last month as run_end, and the number of months in it as months_active. Sort by merchant_id and then by run_start.

Asked of

  • Data Analyst
  • Business Analyst
  • BI Analyst
  • Product Analyst
  • Analytics Engineer
  • Data Engineer
  • Data Scientist

shopify_subscriptionsTable26 rows

Column NameType
record_idBIGINT
merchant_idVARCHAR
active_monthDATE
planVARCHAR
mrrDOUBLE

shopify_subscriptionsExample Input

record_idmerchant_idactive_monthplanmrr
1101M012024-01-01Basic29
1102M012024-02-01Basic29
1103M012024-03-01Shopify79
1104M012024-06-01Shopify79
1105M012024-07-01Advanced299
1106M012024-08-01Advanced299
1119M042024-01-01Advanced299
1120M042024-02-01Advanced299
1121M042024-03-01Advanced299
1122M042024-04-01Advanced299

Example Output

merchant_idrun_startrun_endmonths_active
M012024-01-012024-03-013
M012024-06-012024-08-013
M042024-01-012024-04-014

Explanation

M01 paid for three months, left for two, and came back for three more. That is two runs rather than one relationship of six months. M04 paid for four months without a break, so it has a single run.

The example above is a small slice of the data. Your query runs against the full tables.