Quarter-over-Quarter Revenue Analysis with Same-Store Metrics
SQL & DataAuto-gradedLast updated
Build a SQL query that compares quarterly performance across different time periods, handling store openings/closings and computing both total and same-store growth rates.
You work as a data analyst for a retail beverage business. Leadership wants to understand whether the second quarter of 2024 showed genuine performance weakness. Your task is to write a single SQL query that produces a comprehensive comparison table.
You have three tables:
transactions table:
transaction_id(BIGINT): unique identifiersale_date(DATE): when the transaction occurredstore_id(INT): which locationproduct_id(INT): which itemunits(INT): quantity soldrevenue(DECIMAL(10,2)): dollar amountis_return(BOOLEAN): whether this was a customer return
stores table:
store_id(INT): location identifierregion(VARCHAR): geographic areaopened_date(DATE): when the store started operatingclosed_date(DATE, nullable): when the store shut down, or NULL if still open
products table:
product_id(INT): item identifiercategory(VARCHAR): product type
Sample data:
transactions:
transaction_id | sale_date | store_id | product_id | units | revenue | is_return
1 | 2024-03-30 | 101 | 11 | 10 | 50.00 | false
2 | 2024-04-02 | 101 | 11 | 8 | 44.00 | false
3 | 2024-04-15 | 102 | 12 | 5 | 40.00 | false
4 | 2024-05-01 | 103 | 11 | -1 | -5.50 | true
5 | 2024-06-20 | 101 | 12 | 7 | 63.00 | false
6 | 2023-06-10 | 101 | 11 | 9 | 45.00 | false
stores:
store_id | region | opened_date | closed_date
101 | West | 2020-01-01 | NULL
102 | East | 2021-05-10 | NULL
103 | North | 2024-05-01 | 2024-07-15
products:
product_id | category
11 | Soda
12 | Juice
Your query must:
-
Define quarters using calendar boundaries: Q1 2024 spans 2024-01-01 through 2024-03-31; Q2 2024 spans 2024-04-01 through 2024-06-30; Q2 2023 spans 2023-04-01 through 2023-06-30.
-
Generate exactly two rows of output:
Q2_2024_vs_Q1_2024(sequential quarter comparison)Q2_2024_vs_Q2_2023(year-over-year comparison)
-
For each comparison row, calculate these columns:
total_revenue_period_a,total_revenue_period_b: aggregate revenue for each periodrevenue_pct_change: percent change from period B to period Atotal_units_period_a,total_units_period_b: aggregate unit salesunits_pct_change: percent change in unitsavg_price_period_a,avg_price_period_b: calculated as total revenue divided by total unitssame_store_revenue_pct_change: revenue growth considering only stores that operated continuously throughout both periods being comparedactive_store_count_a,active_store_count_b: number of stores that were operational during each perioddecline_flag: TRUE if both revenue and units fell by more than 5%, otherwise FALSE
-
Handle returns correctly—they already appear as negative values in the data and should net against positive sales.
-
A store qualifies for "same-store" analysis only if it was open for the complete duration of both periods in the comparison (opened on or before the earlier period begins, and either never closed or closed after the later period ends).
-
Avoid data duplication issues from joins and compute aggregates at the correct level before calculating ratios.
Write standard ANSI SQL using CTEs and window functions as needed. No UDFs or database-specific extensions.
Hints
Hint 1
Aggregate transactions to the day-store-product grain before joining to other tables to prevent row duplication
Hint 2
Calculate period-level sums first, then compute ratios—never average pre-computed averages
Hint 3
The 'same-store' set differs between sequential and year-over-year comparisons since the eligibility windows are different
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests your ability to perform period-over-period business analytics while avoiding three common pitfalls:
1. Row multiplication from improper joins
If you join the transactions table directly to stores before aggregating, and a store has metadata spread across multiple dimensions, you can accidentally duplicate transaction rows. The solution is to aggregate transactions to a consistent grain first.
2. Incorrect averaging
Computing daily averages and then averaging those produces misleading results because it gives equal weight to slow and busy days. Instead, sum all revenue and all units at the period level, then divide once.
3. Store mix effects
When new stores open or existing ones close, total revenue changes even if underlying performance is stable. Same-store metrics isolate organic growth by comparing only locations that operated throughout both periods.
Solution Structure
Step 1: Define periods and comparisons
Create CTEs that enumerate the date ranges for each quarter and specify which periods to compare. This avoids hardcoding dates repeatedly.
Step 2: Establish transaction grain
Aggregate the transactions table to one row per (sale_date, store_id, product_id) combination. Returns are already negative, so simple summation nets them out correctly.
Step 3: Aggregate to periods
Roll up the daily data to period-level totals per store. Since periods don't overlap, each transaction appears in exactly one period.
Step 4: Compute overall metrics
Sum across all stores for each period to get total revenue and units. Calculate average price as the ratio of these sums.
Step 5: Identify same-store cohorts
For each comparison, determine which stores operated throughout both complete periods. A store qualifies only if it opened before or on the start of the earlier period and didn't close before the end of the later period.
Step 6: Calculate same-store performance
Compute revenue totals considering only the eligible store set for each comparison.
Step 7: Assemble output
Join all metrics together and compute percentage changes. Mark comparisons showing declines exceeding 5% in both revenue and units.
SQL Implementation
WITH periods AS (
SELECT 'Q1_2024' AS period_id,
DATE '2024-01-01' AS start_dt,
DATE '2024-03-31' AS end_dt
UNION ALL
SELECT 'Q2_2024', DATE '2024-04-01', DATE '2024-06-30'
UNION ALL
SELECT 'Q2_2023', DATE '2023-04-01', DATE '2023-06-30'
),
comparisons AS (
SELECT 'Q2_2024_vs_Q1_2024' AS label,
'Q2_2024' AS current_period,
'Q1_2024' AS baseline_period,
1 AS display_order
UNION ALL
SELECT 'Q2_2024_vs_Q2_2023', 'Q2_2024', 'Q2_2023', 2
),
-- Aggregate to day-store-product grain to prevent duplication
daily_aggregated AS (
SELECT sale_date,
store_id,
product_id,
SUM(units) AS daily_units,
SUM(revenue) AS daily_revenue
FROM transactions
WHERE sale_date BETWEEN DATE '2023-04-01' AND DATE '2024-06-30'
GROUP BY sale_date, store_id, product_id
),
-- Roll up to period-store level
period_store_data AS (
SELECT p.period_id,
d.store_id,
SUM(d.daily_units) AS store_units,
SUM(d.daily_revenue) AS store_revenue
FROM daily_aggregated d
INNER JOIN periods p
ON d.sale_date BETWEEN p.start_dt AND p.end_dt
GROUP BY p.period_id, d.store_id
),
-- Overall period totals
period_aggregates AS (
SELECT p.period_id,
COALESCE(SUM(ps.store_revenue), 0) AS total_revenue,
COALESCE(SUM(ps.store_units), 0) AS total_units
FROM periods p
LEFT JOIN period_store_data ps
ON ps.period_id = p.period_id
GROUP BY p.period_id
),
-- Count stores operating during each period
stores_active AS (
SELECT p.period_id,
COUNT(s.store_id) AS store_count
FROM periods p
LEFT JOIN stores s
ON s.opened_date <= p.end_dt
AND (s.closed_date IS NULL OR s.closed_date >= p.start_dt)
GROUP BY p.period_id
),
-- Identify stores open for both full periods in each comparison
same_store_cohort AS (
SELECT c.label AS comparison_label,
s.store_id
FROM comparisons c
INNER JOIN periods p_curr ON p_curr.period_id = c.current_period
INNER JOIN periods p_base ON p_base.period_id = c.baseline_period
INNER JOIN stores s
ON s.opened_date <= LEAST(p_curr.start_dt, p_base.start_dt)
AND (s.closed_date IS NULL
OR s.closed_date >= GREATEST(p_curr.end_dt, p_base.end_dt))
),
-- Same-store revenue by comparison
same_store_metrics AS (
SELECT c.label AS comparison_label,
SUM(CASE WHEN ps.period_id = c.current_period
THEN ps.store_revenue ELSE 0 END) AS ss_revenue_current,
SUM(CASE WHEN ps.period_id = c.baseline_period
THEN ps.store_revenue ELSE 0 END) AS ss_revenue_baseline
FROM comparisons c
INNER JOIN same_store_cohort ssc
ON ssc.comparison_label = c.label
LEFT JOIN period_store_data ps
ON ps.store_id = ssc.store_id
AND ps.period_id IN (c.current_period, c.baseline_period)
GROUP BY c.label
),
-- Join all metrics together
final_metrics AS (
SELECT c.label,
c.display_order,
pa_curr.total_revenue AS total_revenue_period_a,
pa_base.total_revenue AS total_revenue_period_b,
100.0 * (pa_curr.total_revenue - pa_base.total_revenue)
/ NULLIF(pa_base.total_revenue, 0) AS revenue_pct_change,
pa_curr.total_units AS total_units_period_a,
pa_base.total_units AS total_units_period_b,
100.0 * (pa_curr.total_units - pa_base.total_units)
/ NULLIF(pa_base.total_units, 0) AS units_pct_change,
pa_curr.total_revenue / NULLIF(pa_curr.total_units, 0) AS avg_price_period_a,
pa_base.total_revenue / NULLIF(pa_base.total_units, 0) AS avg_price_period_b,
100.0 * (ssm.ss_revenue_current - ssm.ss_revenue_baseline)
/ NULLIF(ssm.ss_revenue_baseline, 0) AS same_store_revenue_pct_change,
sa_curr.store_count AS active_store_count_a,
sa_base.store_count AS active_store_count_b
FROM comparisons c
INNER JOIN period_aggregates pa_curr
ON pa_curr.period_id = c.current_period
INNER JOIN period_aggregates pa_base
ON pa_base.period_id = c.baseline_period
INNER JOIN stores_active sa_curr
ON sa_curr.period_id = c.current_period
INNER JOIN stores_active sa_base
ON sa_base.period_id = c.baseline_period
LEFT JOIN same_store_metrics ssm
ON ssm.comparison_label = c.label
)
SELECT label AS comparison,
total_revenue_period_a,
total_revenue_period_b,
revenue_pct_change,
total_units_period_a,
total_units_period_b,
units_pct_change,
avg_price_period_a,
avg_price_period_b,
same_store_revenue_pct_change,
active_store_count_a,
active_store_count_b,
CASE WHEN revenue_pct_change < -5 AND units_pct_change < -5
THEN TRUE ELSE FALSE END AS decline_flag
FROM final_metrics
ORDER BY display_order;
Key Design Decisions
Grain enforcement: The daily_aggregated CTE ensures exactly one row per date-store-product combination before any joins. This prevents the fan-out problem where joining dimensional tables multiplies transaction rows.
Period-level division: Average prices are computed as SUM(revenue) / SUM(units) at the period level. This correctly weights high-volume stores. Computing per-store or per-day averages first and then averaging those would give equal weight to all entities regardless of volume.
Comparison-specific same-store sets: Each comparison has its own eligibility window. For Q2 vs Q1, a store must be open from January 1 through June 30. For Q2 2024 vs Q2 2023, it must be open from April 1, 2023 through June 30, 2024. Using a single global set would incorrectly exclude or include stores.
Return handling: Returns already appear with negative units and revenue values in the data. Using SUM directly nets returns against sales automatically. Filtering out returns would overstate performance.
NULL safety: All divisions use NULLIF to prevent divide-by-zero errors. The decline flag evaluates to FALSE when percentage changes are NULL, avoiding false positives.
Complexity
- Time: O(n) where n is the number of transaction rows—each row is scanned once and aggregated through multiple levels
- Space: O(s × p) where s is the number of stores and p is the number of periods, for the intermediate period-store aggregates
Common Mistakes
- Joining stores before aggregating transactions, causing row duplication
- Computing average-of-averages instead of sum-then-divide
- Using a single same-store cohort for all comparisons
- Filtering out returns instead of netting them as negative values
- Not handling NULL closed dates when determining store eligibility
- Declaring decline based only on revenue without checking units