#215
Subscription Expiry Date Calculation
MEDIUMWindow FunctionsPOSTGRESQL
Problem Description
A subscription analytics platform needs to compute the effective end date for every subscription record. This `expiry_dt` field is consumed downstream by churn models, renewal reminder pipelines, and cohort analysis jobs.
You are given a `sales` table that contains both purchase and refund events for subscriptions. Each purchase record has a `plan` type and may be followed by a refund row for the same `user_id` and `product_id`.
**Plan Duration:**
- `monthly` plan: expiry = `transaction_dt + 1 month`
- `yearly` plan: expiry = `transaction_dt + 1 year`
**Refund Override Rule:**
- If a purchase has a subsequent refund (same user + product, next transaction is `category = 'refund'`), the `expiry_dt` is the refund's `transaction_dt` instead of the plan's natural end date.
**Output:** Return only purchase rows (not refund rows) with columns `user_id`, `product_id`, `transaction_dt`, `price`, `plan`, and `expiry_dt`. Order by `user_id`, `product_id`, `transaction_dt`.
Topics
window functionsdate functions
Asked at Companies
atlassian
Solve This Problem
Sign up to access the interactive code editor, run test cases, view the editorial, and get AI-powered feedback on your solution.
Start Solving →