The Shape of the Year

A medium SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
medium
Seniority
L3
Asked in
Capital One

Problem

We're tracing a retail marketplace's revenue as it moves month by month across the calendar. For each month, report the total revenue, the number of transactions, and the average transaction value, earliest month first.

Revenue has a rhythm. Trace it, month by month.

Tables

transactions

Columns: transaction_id INTEGER, user_id INTEGER, product_id INTEGER, quantity INTEGER, total_amount REAL, transaction_date TEXT

transactions: 10 of 200 rows
transaction_iduser_idproduct_idquantitytotal_amounttransaction_date
10671971001223.462026-02-02
11342941050336.932026-03-03
12013911099450.42026-04-04
12684881148563.872026-05-05
13355851197002026-06-06
14026821246290.812026-07-07
146977912953104.282026-08-08
153687613444117.752026-09-09
160397313935-452026-01-10
1670107014421144.692026-02-11

Expected output

First 5 of 57 rows
monthtotal_revenuenum_transactionsavg_transaction_value
2022-01855.122427.56
2022-021528.62000000000012764.3100000000001
2022-03696.961696.96
2026-0110187.3714727.6692857142858
2026-038508.2113654.4776923076922

Worked solution and explanation

What this really tests

This is a monthly rollup wearing a revenue-analysis costume. The only real skill: turn a raw transaction_date into a month bucket and pick a grain where each calendar month collapses to exactly one row. Everyone can type SUM and COUNT. The tell is whether your GROUP BY key is the exact same expression you SELECT as the bucket, so the two can never drift apart, and whether your average is revenue over transaction count rather than an average of some finer grain. Get the grain wrong and you either split one month across many rows or quietly average the wrong denominator.


Building it up

Step 1: Derive the month key

Derive the month key with strftime('%Y-%m', transaction_date). This yields a zero-padded string like 2026-04 that carries both year and month, and it is the shared bucket for every transaction in that month.

Step 2: Collapse each month

GROUP BY the month key so every transaction in the same year-month folds into a single row. Because the key includes the year, February 2025 and February 2026 stay separate.

Step 3: Compute the three metrics

Per month compute SUM(total_amount) as total revenue, COUNT(*) as the transaction count, and SUM(total_amount) / COUNT(*) as the average transaction value. Order by the month key so the timeline reads front to back.


The solution

Monthly revenue rollup
SELECT strftime('%Y-%m', transaction_date) AS month,
       SUM(total_amount) AS total_revenue,
       COUNT(*) AS num_transactions,
       SUM(total_amount) / COUNT(*) AS avg_transaction_value
FROM transactions
GROUP BY month
ORDER BY month

Common follow-up questions