AnalystPath

Plan Price on a Given Date

SQLMediumMid level~15 min

Problem

Table: `PriceChanges`

```text
+-------------+---------+
| Column | Type |
+-------------+---------+
| plan_id | int |
| new_price | int |
| effective_on| date |
+-------------+---------+
There is no single-column primary key (a plan can change price many times).
Each row records that plan_id's price became new_price on effective_on.
```

Every plan starts at a base price of **20** before its first recorded change.
Return the price of each plan **as of 2024-07-01** (the most recent change on
or before that date, or 20 if there is none). Return `plan_id` and a column
named `price`.

**Example**

```text
PriceChanges:
+---------+-----------+--------------+
| plan_id | new_price | effective_on |
+---------+-----------+--------------+
| 1 | 35 | 2024-05-01 |
| 1 | 40 | 2024-08-01 |
| 2 | 25 | 2024-06-15 |
| 3 | 50 | 2024-09-01 |
+---------+-----------+--------------+

Output:
+---------+-------+
| plan_id | price |
+---------+-------+
| 1 | 35 |
| 2 | 25 |
| 3 | 20 |
+---------+-------+
```

Plan 1's latest change on or before 2024-07-01 set the price to 35 (the
2024-08-01 change is in the future). Plan 3's only change is after the date,
so it keeps the base price of 20.

Tables

Example rows — the live problem includes the full dataset.

PriceChanges
plan_idnew_priceeffective_on
1352024-05-01
1402024-08-01
2252024-06-15

Expected output

Your answer should return 3 rows with the columns plan_id, price.

Starter code (SQL)

SELECT *
FROM PriceChanges;

Solve this SQL question free

Write SQL and run it instantly in your browser — even on your phone. No signup needed to try.

Solution & explanation

Create a free account to unlock the optimal solution, a step-by-step explanation, and the hidden test cases that grade your answer.

Sign up free to unlock

Related SQL questions