Weekly Revenue Aggregation and Regional Drop Attribution
SQL & DataModel answerLast updated
Aggregate weekly revenue in SQL using ISO weeks, calculate period-over-period performance, and attribute regional drop drivers with guardrails against incomplete weeks.
You are analyzing transactional data to monitor weekly financial performance and diagnose revenue drops across geographic regions.
Write SQL queries for the table orders to accomplish three tasks:
-
Task A (Weekly Aggregation): Aggregate total sales revenue by calendar week (ISO standard: Monday through Sunday) across all completed orders. Exclude order records marked as cancelled or refunded.
- Revenue calculation formula:
revenue_usd = subtotal_usd + tax_usd + delivery_fee_usd - discount_usd. - Ensure weeks without orders are filled with zeros if applicable, and explicitly identify whether each week is complete or partial relative to the maximum timestamp in the table.
- Revenue calculation formula:
-
Task B (Week-over-Week Change): Calculate the absolute financial change (
delta_usd) and percentage change (pct_change) between the last two fully completed weeks based on the most recent order timestamp in the dataset. -
Task C (Regional Attribution): If the revenue for the latest complete week declined by 4% or more ($\le -4%$) relative to the prior complete week, list the top 3 geographic regions (
geo) contributing most to the overall net negative drop. Include each region's revenue for both weeks, its absolute loss, its percentage change, and its share of the total absolute drop across all regions.
Table Schema: orders
| Column Name | Data Type | Notes |
|---|---|---|
order_id | INT | Primary key |
user_id | INT | User identifier |
order_ts | TIMESTAMP | Timestamp in UTC |
geo | VARCHAR(10) | Geographic market code (e.g., 'MIA', 'ATL', 'NYC') |
status | VARCHAR(20) | Order status: 'completed', 'cancelled', 'refunded' |
subtotal_usd | DECIMAL(10,2) | Base item total |
tax_usd | DECIMAL(10,2) | Tax charged |
delivery_fee_usd | DECIMAL(10,2) | Delivery surcharge |
discount_usd | DECIMAL(10,2) | Promotional discounts subtracted |
Sample Data
| order_id | user_id | order_ts | geo | status | subtotal_usd | tax_usd | delivery_fee_usd | discount_usd |
|---|---|---|---|---|---|---|---|---|
| 1 | 101 | 2025-08-12 14:00:00 | MIA | completed | 50.00 | 3.50 | 5.99 | 0.00 |
| 2 | 102 | 2025-08-13 16:00:00 | MIA | completed | 40.00 | 2.80 | 5.99 | 5.00 |
| 3 | 103 | 2025-08-18 12:00:00 | ATL | completed | 60.00 | 4.20 | 0.00 | 0.00 |
| 4 | 104 | 2025-08-19 10:00:00 | ATL | cancelled | 35.00 | 2.45 | 0.00 | 0.00 |
| 5 | 105 | 2025-08-20 09:00:00 | MIA | completed | 30.00 | 2.10 | 5.99 | 0.00 |
| 6 | 106 | 2025-08-20 18:00:00 | NYC | completed | 80.00 | 5.60 | 0.00 | 10.00 |
| 7 | 107 | 2025-08-25 13:30:00 | NYC | refunded | 20.00 | 1.40 | 0.00 | 0.00 |
| 8 | 108 | 2025-08-26 15:15:00 | MIA | completed | 55.00 | 3.85 | 5.99 | 0.00 |
Specific Business Rules & Edge Cases
- Use
DATE_TRUNC('week', order_ts)(PostgreSQL syntax) to establish Monday-start ISO calendar weeks. - The current week containing
MAX(order_ts)must be treated as incomplete and excluded from period-over-period comparisons. - Handle missing values safely using
COALESCE. - Only consider orders where
status = 'completed'.
Hints
Hint 1
To determine the anchor for completed weeks, find MAX(order_ts) and truncate it to the start of its week. The last complete week ended right before this timestamp.
Hint 2
You can use conditional aggregation (SUM FILTER or CASE WHEN) across timestamp ranges relative to the latest week anchor to compute prior and latest complete week revenues in a single pass.
Hint 3
When evaluating regional contributions to a revenue drop, remember that some regions may grow while others shrink. Calculate each region's delta (latest - prior) and sort by ascending delta to highlight the largest drops.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Technical Walkthrough
To solve this problem correctly in PostgreSQL, we need to handle three key analytical mechanics:
- ISO Week Truncation & Partial Week Filtering:
DATE_TRUNC('week', ts)truncates timestamps to Monday at00:00:00. IfMAX(order_ts)falls on a Tuesday, the week starting on that Monday is incomplete. Therefore, the last complete week starts 7 days prior (cur_week - INTERVAL '7 days'), and the prior complete week starts 14 days prior (cur_week - INTERVAL '14 days'). - Missing Time Buckets: Using a generated date spine ensures continuous reporting even if certain weeks have zero completed orders.
- Attribution Gating: Task C requires checking if the aggregate drop is $\le -4%$. If the company grew or dropped by less than 4%, the query should return zero rows while keeping the output schema intact.
SQL Implementation
Task A: Weekly Revenue Time-Series
WITH bounds AS (
SELECT
DATE_TRUNC('week', MIN(order_ts)) AS start_week,
DATE_TRUNC('week', MAX(order_ts)) AS cur_week
FROM orders
),
week_spine AS (
SELECT
generate_series(start_week, cur_week, INTERVAL '1 week') AS week_start
FROM bounds
),
weekly_aggregates AS (
SELECT
DATE_TRUNC('week', order_ts) AS week_start,
SUM(
COALESCE(subtotal_usd, 0) +
COALESCE(tax_usd, 0) +
COALESCE(delivery_fee_usd, 0) -
COALESCE(discount_usd, 0)
) AS revenue_usd,
COUNT(*) AS completed_order_count
FROM orders
WHERE status = 'completed'
GROUP BY 1
)
SELECT
s.week_start::date AS week_start,
(s.week_start + INTERVAL '6 days')::date AS week_end,
COALESCE(w.revenue_usd, 0)::numeric(14,2) AS revenue_usd,
COALESCE(w.completed_order_count, 0)::int AS completed_order_count,
(s.week_start < b.cur_week) AS is_complete_week
FROM week_spine s
CROSS JOIN bounds b
LEFT JOIN weekly_aggregates w USING (week_start)
ORDER BY s.week_start;
Task B: Period-over-Period Performance (Last 2 Completed Weeks)
WITH anchor AS (
SELECT DATE_TRUNC('week', MAX(order_ts)) AS cur_week
FROM orders
),
period_sums AS (
SELECT
a.cur_week,
COALESCE(SUM(
subtotal_usd + tax_usd + delivery_fee_usd - discount_usd
) FILTER (
WHERE order_ts >= a.cur_week - INTERVAL '7 days'
AND order_ts < a.cur_week
), 0) AS last_complete_week_rev,
COALESCE(SUM(
subtotal_usd + tax_usd + delivery_fee_usd - discount_usd
) FILTER (
WHERE order_ts >= a.cur_week - INTERVAL '14 days'
AND order_ts < a.cur_week - INTERVAL '7 days'
), 0) AS prior_complete_week_rev
FROM orders o
CROSS JOIN anchor a
WHERE o.status = 'completed'
GROUP BY a.cur_week
)
SELECT
(cur_week - INTERVAL '14 days')::date AS prior_week_start,
(cur_week - INTERVAL '7 days')::date AS last_week_start,
prior_complete_week_rev::numeric(14,2) AS prior_week_revenue_usd,
last_complete_week_rev::numeric(14,2) AS last_week_revenue_usd,
(last_complete_week_rev - prior_complete_week_rev)::numeric(14,2) AS delta_usd,
ROUND(
100.0 * (last_complete_week_rev - prior_complete_week_rev) /
NULLIF(prior_complete_week_rev, 0), 2
) AS pct_change
FROM period_sums;
Task C: Regional Drop Attribution ($\le -4%$ Threshold)
WITH anchor AS (
SELECT DATE_TRUNC('week', MAX(order_ts)) AS cur_week
FROM orders
),
geo_breakdown AS (
SELECT
COALESCE(o.geo, 'UNKNOWN') AS geo,
COALESCE(SUM(
subtotal_usd + tax_usd + delivery_fee_usd - discount_usd
) FILTER (
WHERE order_ts >= a.cur_week - INTERVAL '7 days'
AND order_ts < a.cur_week
), 0) AS last_complete_week_rev,
COALESCE(SUM(
subtotal_usd + tax_usd + delivery_fee_usd - discount_usd
) FILTER (
WHERE order_ts >= a.cur_week - INTERVAL '14 days'
AND order_ts < a.cur_week - INTERVAL '7 days'
), 0) AS prior_complete_week_rev
FROM orders o
CROSS JOIN anchor a
WHERE o.status = 'completed'
GROUP BY 1
),
company_totals AS (
SELECT
SUM(last_complete_week_rev) AS total_last_rev,
SUM(prior_complete_week_rev) AS total_prior_rev
FROM geo_breakdown
)
SELECT
g.geo,
g.prior_complete_week_rev::numeric(14,2) AS prior_week_revenue_usd,
g.last_complete_week_rev::numeric(14,2) AS last_week_revenue_usd,
(g.last_complete_week_rev - g.prior_complete_week_rev)::numeric(14,2) AS geo_delta_usd,
ROUND(
100.0 * (g.last_complete_week_rev - g.prior_complete_week_rev) /
NULLIF(t.total_last_rev - t.total_prior_rev, 0), 2
) AS share_of_total_delta_pct,
ROUND(
100.0 * (g.last_complete_week_rev - g.prior_complete_week_rev) /
NULLIF(g.prior_complete_week_rev, 0), 2
) AS geo_pct_change
FROM geo_breakdown g
CROSS JOIN company_totals t
-- Gate: trigger only if aggregate total revenue dropped by >= 4%
WHERE (t.total_last_rev - t.total_prior_rev) / NULLIF(t.total_prior_rev, 0) <= -0.04
ORDER BY geo_delta_usd ASC, g.geo ASC
LIMIT 3;
Step-by-Step Execution on Sample Data
-
Max Timestamp Analysis:
MAX(order_ts)is2025-08-26 15:15:00(Tuesday).cur_week=2025-08-25 00:00:00(Incomplete week, excluded from WoW comparison).last_complete_week=2025-08-18to2025-08-24.prior_complete_week=2025-08-11to2025-08-17.
-
Completed Orders Calculation:
- Prior Complete Week (
2025-08-11):- Order 1 (MIA): $50.00 + 3.50 + 5.99 - 0 = $59.49$
- Order 2 (MIA): $40.00 + 2.80 + 5.99 - 5.00 = $43.79$
- Total = $103.28
- Last Complete Week (
2025-08-18):- Order 3 (ATL): $60.00 + 4.20 + 0 - 0 = $64.20$
- Order 5 (MIA): $30.00 + 2.10 + 5.99 - 0 = $38.09$
- Order 6 (NYC): $80.00 + 5.60 + 0 - 10.00 = $75.60$
- Total = $177.89
- Prior Complete Week (
-
Task B Result:
prior_week_revenue_usd= 103.28last_week_revenue_usd= 177.89delta_usd= $+74.61$pct_change= $+72.24%$
-
Task C Result:
- Because overall revenue grew ($+72.24%$), the gating condition (
pct_change <= -0.04) evaluates toFALSE. Task C produces 0 rows as expected.
- Because overall revenue grew ($+72.24%$), the gating condition (
Complexity Analysis
- Time Complexity: $\mathcal{O}(N \log N)$ where $N$ is the number of rows in
orders, driven by the grouping and date truncation operations. With proper indexing on(status, order_ts), performance drops to $\mathcal{O}(M)$ for filtering completed transactions. - Space Complexity: $\mathcal{O}(W + G)$ where $W$ is the number of distinct weeks and $G$ is the number of distinct regions stored in CTE buffers.