Retail Spend Analytics: Aggregation and Regional Rankings
SQL & DataModel answerLast updated
Write two SQL queries against a payment dataset to find top vendors globally and per region using aggregation, joins, and window-based dense ranking.
Retail Spend Analytics
You work with a payment processing dataset containing two tables.
transactions
| column | type | description |
|---|---|---|
transaction_id | integer | Unique identifier for each transaction. |
user_id | integer | Identifier for the customer who made the transaction. |
vendor_id | integer | Identifier for the merchant. |
transaction_time | timestamp | When the transaction was recorded. |
transaction_dollars | numeric | Dollar value of the transaction. |
transaction_type | text | Either PURCHASE or REFUND. |
refund_transaction_id | integer | For REFUND rows only: the transaction_id of the original purchase. |
vendors
| column | type | description |
|---|---|---|
vendor_id | integer | Unique identifier for each merchant. |
city | text | City where the merchant operates. |
state_province | text | State or province of the merchant. |
country | text | Two-letter country code. |
Rules
- Only
PURCHASErows represent money charged.REFUNDrows should be excluded from all totals. - "The last 2 years" means a rolling window: any transaction recorded at or after
CURRENT_TIMESTAMP - INTERVAL '2 years'.
Task 1
Find the three merchants who collected the most purchase dollars over the last 2 years, globally. Return vendor_id and total_dollars_charged, ordered from highest to lowest. Break ties by vendor_id ascending so the result is deterministic.
Task 2
For every (state_province, country) pair, identify the top 3 merchants by total purchase dollars over the same 2-year window. Return state_province, country, vendor_id, total_dollars, and vendor_rank. Rank using dense ranking so merchants with identical totals share a rank — this means a location can return more than 3 rows when there are ties at rank 3.
Write your queries in PostgreSQL syntax. Be prepared to discuss how you would adapt the date arithmetic for other dialects, and what changes if the business asks for net spend (purchases minus refunds) instead of gross spend.
Hints
Hint 1
Aggregate and filter before you join — sum transaction rows by vendor_id first, then bring in vendor location metadata. Joining first and aggregating second risks row fan-out if the join isn't strictly 1-to-1 in practice, and it also makes the intent harder to read.
Hint 2
Window functions are evaluated after WHERE and HAVING, so you cannot filter on a window-function result in the same query level where you compute it. Wrap it in a CTE or subquery, then apply the rank filter in the outer SELECT.
Hint 3
Think carefully about what dense ranking means for the output row count. If two vendors tie for third place in a region, DENSE_RANK gives both rank 3 and your WHERE vendor_rank <= 3 returns four rows for that region — that is the correct, intended behavior. Contrast this with RANK (skips numbers) and ROW_NUMBER (breaks ties arbitrarily).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Both tasks share the same three-step skeleton: filter to purchases in the window → aggregate dollars per vendor → rank or limit. The differences are that Task 2 adds a location join and a per-partition window function where Task 1 only needs a plain sort and LIMIT.
Task 1 — Global Top 3
SELECT
t.vendor_id,
SUM(t.transaction_dollars) AS total_dollars_charged
FROM transactions t
WHERE t.transaction_type = 'PURCHASE'
AND t.transaction_time >= CURRENT_TIMESTAMP - INTERVAL '2 years'
GROUP BY t.vendor_id
ORDER BY total_dollars_charged DESC, t.vendor_id ASC
LIMIT 3;
The transaction_type filter belongs in WHERE, not in a CASE inside SUM. Both approaches produce correct totals, but the WHERE predicate lets the engine use an index and skip refund rows entirely before aggregation. The secondary sort on vendor_id makes the output deterministic when two vendors tie at the cutoff.
Task 2 — Dense Top 3 Per Region
WITH vendor_totals AS (
SELECT
t.vendor_id,
SUM(t.transaction_dollars) AS total_dollars
FROM transactions t
WHERE t.transaction_type = 'PURCHASE'
AND t.transaction_time >= CURRENT_TIMESTAMP - INTERVAL '2 years'
GROUP BY t.vendor_id
),
ranked AS (
SELECT
v.state_province,
v.country,
vt.vendor_id,
vt.total_dollars,
DENSE_RANK() OVER (
PARTITION BY v.state_province, v.country
ORDER BY vt.total_dollars DESC
) AS vendor_rank
FROM vendor_totals vt
JOIN vendors v ON v.vendor_id = vt.vendor_id
)
SELECT
state_province,
country,
vendor_id,
total_dollars,
vendor_rank
FROM ranked
WHERE vendor_rank <= 3
ORDER BY country, state_province, vendor_rank, vendor_id;
Why Each Decision Matters
Aggregate before joining. The vendor_totals CTE reduces the transaction table to one row per vendor before the join. Since vendors also has one row per vendor_id, the join is guaranteed 1-to-1 and cannot inflate totals. Joining first and grouping second is still correct here, but it forces the engine to carry all transaction columns through the join, and any future schema change that breaks the uniqueness assumption would silently multiply rows.
Partition by both columns. Using PARTITION BY state_province, country rather than just state_province is important: the state code "GA" exists in both the US (Georgia) and other regions, and a province name like "Ontario" could theoretically appear in multiple countries. Partitioning on both columns keeps those groups separate.
Dense ranking semantics. With totals 500, 500, 400, 300, the ranks are 1, 1, 2, 3. A WHERE vendor_rank <= 3 filter returns all four rows — that is correct given the prompt. RANK would produce 1, 1, 3, 4 and still return the same four rows here, but it skips rank 2, which is unintuitive. ROW_NUMBER breaks ties arbitrarily and always returns exactly 3 rows, which is wrong when ties should be preserved.
Why the rank filter must be in an outer query. Window functions are computed in the logical order of operations after WHERE and HAVING. You cannot write WHERE DENSE_RANK() OVER (...) <= 3 — the engine hasn't computed it yet at that stage. The CTE pattern is the standard solution; Snowflake and BigQuery also support QUALIFY vendor_rank <= 3 as a shorthand.
Complexity
Let N = transaction rows, V = distinct vendors with purchases in the window.
- Scan and filter: O(N), ideally short-circuited by an index on
(transaction_type, transaction_time). - Aggregation: O(N) with hash aggregation, producing V groups.
- Join: O(V) with a hash join against the vendors table.
- Window sort: O(V log V) for the
DENSE_RANKcomputation. - Space: O(V) for the aggregation hash table and window partitions.
At production scale, a partial index WHERE transaction_type = 'PURCHASE' on transaction_time cuts scan cost significantly. Range partitioning transactions by month lets the planner prune all partitions outside the 2-year window before touching a single row.
Edge Cases Worth Raising
"Last 2 years" definition. CURRENT_TIMESTAMP - INTERVAL '2 years' is a rolling window precise to the second. If the business defines it as calendar days, use CURRENT_DATE - INTERVAL '2 years'. If future-dated rows are possible (data entry errors, pre-authorized transactions), add AND transaction_time <= CURRENT_TIMESTAMP.
Vendors absent from the vendors table. The inner join in Task 2 silently drops any vendor_id that has no metadata row. That vendor still appears in Task 1. Use a LEFT JOIN in Task 2 and decide whether unknown-location vendors belong in their own group or should be excluded entirely.
NULL location values. PARTITION BY groups NULL state_province or NULL country values together, so all vendors missing location data share one partition. That may or may not be meaningful — worth filtering them out or labeling them explicitly depending on the use case.
Net spend follow-up. To compute purchases minus refunds, remove the type filter and replace the SUM with:
SUM(
CASE
WHEN transaction_type = 'REFUND' THEN -ABS(transaction_dollars)
ELSE transaction_dollars
END
) AS net_dollars
A subtler question is whether a refund that falls inside the 2-year window for a purchase that falls outside it should count. The refund_transaction_id column lets you join back to the original purchase to enforce consistency if needed.
Dialect Notes
| Engine | 2-year interval | Top-N |
|---|---|---|
| PostgreSQL / Redshift / Snowflake | CURRENT_TIMESTAMP - INTERVAL '2 years' | LIMIT 3 |
| MySQL | NOW() - INTERVAL 2 YEAR | LIMIT 3 |
| SQL Server | DATEADD(year, -2, GETDATE()) | TOP 3 or OFFSET 0 ROWS FETCH NEXT 3 ROWS ONLY |
| BigQuery | TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 730 DAY) | LIMIT 3 |
BigQuery's TIMESTAMP_SUB does not accept YEAR as a unit, so approximating with 730 days or switching to DATE_SUB(CURRENT_DATE(), INTERVAL 2 YEAR) on a date column is the practical workaround.