AnalystPath

Trailing Three-Month Sales, Excluding the Latest Month

SQLHardSenior level~15 min

Problem

Table: `Sales`

```text
+----------+-------+--------+
| Column | Type | |
+----------+-------+--------+
| store_id | int | |
| period | int | |
| revenue | int | |
+----------+-------+--------+
(store_id, period) is the primary key. `period` is a month index that increases over time; periods for a store may have gaps.
```

For each store and each `period`, compute the **trailing three-period revenue**: the sum of that period's revenue plus the two immediately preceding periods (by period order) for the same store. Then **exclude the most recent period of each store** from the output. Return `store_id`, `period`, and the trailing sum as `revenue`, ordered by `store_id` ascending then `period` descending.

Tables

Example rows — the live problem includes the full dataset.

Sales
store_idperiodrevenue
1120
1230
1340

Expected output

Your answer should return 2 rows with the columns store_id, period, revenue.

Starter code (SQL)

SELECT *
FROM Sales;

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