SQL Net Revenue Rankings and Transaction Data Quality Checks
SQL & DataModel answerLast updated
Write SQL queries to rank vendors by net revenue globally and by city/state, then design and implement data quality checks on a transaction table.
Background
You work on a payments data team. Two tables hold the core data.
Table: transactions
| Column | Type | Description |
|---|---|---|
| transaction_id | int | Unique row identifier. |
| vendor_id | int | Vendor who received or refunded the payment. |
| amount_charged | int | Absolute dollar amount of the transaction. |
| transaction_type | varchar | Either PURCHASE or REFUND. |
| refund_transaction_id | int | For refunds: the transaction_id of the original purchase. NULL for purchases. |
| timestamp | datetime | When the transaction occurred. |
Sample data:
| transaction_id | vendor_id | amount_charged | transaction_type | refund_transaction_id | timestamp |
|---|---|---|---|---|---|
| 101 | 1 | 200 | PURCHASE | null | 2025-01-01 |
| 102 | 1 | 150 | PURCHASE | null | 2025-01-10 |
| 103 | 1 | 200 | REFUND | 101 | 2025-01-15 |
| 104 | 2 | 300 | PURCHASE | null | 2025-02-01 |
| 105 | 3 | 500 | PURCHASE | null | 2025-03-01 |
Table: vendors
| Column | Type | Description |
|---|---|---|
| vendor_id | int | Unique vendor identifier. |
| city | varchar | Vendor's city. |
| state | varchar | Vendor's state. |
| country | varchar | Vendor's country. |
Sample data:
| vendor_id | city | state | country |
|---|---|---|---|
| 1 | San Jose | CA | US |
| 2 | San Jose | CA | US |
| 3 | Austin | TX | US |
| 4 | Seattle | WA | US |
| 5 | Dallas | TX | US |
Definitions and assumptions:
- Net revenue = sum of purchases minus sum of refunds for a vendor.
- Use each transaction's own timestamp to decide whether it falls in the window (cash-basis).
- "Past two years" means
>= CURRENT_DATE - INTERVAL '2 years'.
Questions
Q1. Find the top 3 vendors by total net revenue over the past two years, across all locations.
Q2. Within each (state, city) pair, find the top 3 vendors by total net revenue over the past two years.
Q3. Propose at least five meaningful data quality or anomaly checks for this dataset and write a SQL query for each. Think about referential integrity, amount consistency, field validation, orphaned records, and unusual activity patterns.
Hints
Hint 1
For net revenue, a single CASE expression — positive for PURCHASE, negative for REFUND — applied inside SUM is all you need. Build that aggregation in a CTE first, then rank on top of it.
Hint 2
For Q2, partition your window function by both state AND city, not city alone — city names repeat across states. Also join and aggregate in the right order: aggregate transactions first, then join to vendors, so the join cannot accidentally multiply rows.
Hint 3
For Q3, think in layers: row-level validity (nulls, bad enums, negative amounts), referential integrity (does the refund point at a real purchase from the same vendor?), amount consistency (do partial refunds exceed the original?), orphaned vendor IDs, and time-series spikes per vendor using a rolling window.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every question builds on one reusable idea: the signed net amount.
CASE WHEN transaction_type = 'PURCHASE' THEN amount_charged
WHEN transaction_type = 'REFUND' THEN -amount_charged
ELSE 0 END
Put that inside a SUM, filter to the two-year window in WHERE (before aggregation), then rank the totals. Q3 is a collection of independent checks — an empty result set means the check passed.
Assumptions to state before writing code
- Cash-basis vs. purchase-date attribution. Using the refund's own timestamp is simpler and matches "amount charged during the period." Attributing the refund back to the purchase date is the accrual alternative — worth mentioning, but not implemented here.
- Ties.
RANKkeeps all vendors tied for 3rd place.ROW_NUMBERwould arbitrarily drop one. PickRANKand say why. - Future-dated rows. An upper bound guard (
< CURRENT_DATE + INTERVAL '1 day') prevents test or synthetic data from inflating totals.
Q1: Top 3 Vendors by Net Revenue (Global)
WITH vendor_net AS (
SELECT
vendor_id,
SUM(
CASE WHEN transaction_type = 'PURCHASE' THEN amount_charged
WHEN transaction_type = 'REFUND' THEN -amount_charged
ELSE 0 END
) AS net_revenue
FROM transactions
WHERE "timestamp" >= CURRENT_DATE - INTERVAL '2 years'
AND "timestamp" < CURRENT_DATE + INTERVAL '1 day'
GROUP BY vendor_id
),
ranked AS (
SELECT
vendor_id,
net_revenue,
RANK() OVER (ORDER BY net_revenue DESC) AS rnk
FROM vendor_net
)
SELECT vendor_id, net_revenue, rnk
FROM ranked
WHERE rnk <= 3
ORDER BY rnk, vendor_id;
Verification with sample data (assuming all rows fall in the window):
- Vendor 1: 200 + 150 − 200 = 150
- Vendor 2: 300 = 300
- Vendor 3: 500 = 500
Result order: vendor 3 (500), vendor 2 (300), vendor 1 (150).
Q2: Top 3 Vendors per (State, City)
WITH vendor_net AS (
SELECT
vendor_id,
SUM(
CASE WHEN transaction_type = 'PURCHASE' THEN amount_charged
WHEN transaction_type = 'REFUND' THEN -amount_charged
ELSE 0 END
) AS net_revenue
FROM transactions
WHERE "timestamp" >= CURRENT_DATE - INTERVAL '2 years'
AND "timestamp" < CURRENT_DATE + INTERVAL '1 day'
GROUP BY vendor_id
),
ranked AS (
SELECT
v.state,
v.city,
v.vendor_id,
n.net_revenue,
RANK() OVER (
PARTITION BY v.state, v.city
ORDER BY n.net_revenue DESC
) AS rnk
FROM vendor_net n
JOIN vendors v ON v.vendor_id = n.vendor_id
)
SELECT state, city, vendor_id, net_revenue, rnk
FROM ranked
WHERE rnk <= 3
ORDER BY state, city, rnk, vendor_id;
Three design decisions worth explaining:
- Aggregate before joining. Computing
vendor_netfirst keeps the join small and, more importantly, safe — becausevendor_idis the primary key ofvendors, the join cannot fan out rows. - Partition by
(state, city), not justcity. "Springfield" exists in dozens of states; partitioning on city alone would incorrectly merge them. - Inner join intentionally drops unmatched vendors. A transaction with no vendor record has no city, so it cannot appear in a city ranking. Q3 flags those orphans separately.
If you want zero-revenue vendors to appear in the output, start from vendors, left-join vendor_net, and wrap net_revenue in COALESCE(..., 0).
Q3: Data Quality and Anomaly Checks
Check 1 — Duplicate transaction IDs
SELECT transaction_id, COUNT(*) AS occurrences
FROM transactions
GROUP BY transaction_id
HAVING COUNT(*) > 1;
Check 2 — Invalid refund references
Catches refunds pointing at a missing row, a non-purchase row, a different vendor, or a timestamp before the original purchase.
SELECT
r.transaction_id,
r.refund_transaction_id,
CASE
WHEN p.transaction_id IS NULL THEN 'original_missing'
WHEN p.transaction_type <> 'PURCHASE' THEN 'original_not_a_purchase'
WHEN p.vendor_id <> r.vendor_id THEN 'vendor_mismatch'
WHEN r."timestamp" < p."timestamp" THEN 'refund_precedes_purchase'
END AS issue
FROM transactions r
LEFT JOIN transactions p
ON p.transaction_id = r.refund_transaction_id
WHERE r.transaction_type = 'REFUND'
AND (
p.transaction_id IS NULL
OR p.transaction_type <> 'PURCHASE'
OR p.vendor_id <> r.vendor_id
OR r."timestamp" < p."timestamp"
);
Check 3 — Refund amounts exceeding the original purchase
Handles the case where multiple partial refunds collectively exceed what was charged.
SELECT
p.transaction_id,
p.amount_charged AS purchase_amount,
SUM(r.amount_charged) AS total_refunded,
COUNT(*) AS refund_count
FROM transactions p
JOIN transactions r
ON r.refund_transaction_id = p.transaction_id
AND r.transaction_type = 'REFUND'
WHERE p.transaction_type = 'PURCHASE'
GROUP BY p.transaction_id, p.amount_charged
HAVING SUM(r.amount_charged) > p.amount_charged;
Check 4 — Field-level validity
SELECT transaction_id, transaction_type, amount_charged, "timestamp"
FROM transactions
WHERE transaction_type NOT IN ('PURCHASE', 'REFUND')
OR transaction_type IS NULL
OR amount_charged IS NULL
OR amount_charged <= 0
OR "timestamp" IS NULL
OR "timestamp" > CURRENT_TIMESTAMP
OR (transaction_type = 'PURCHASE' AND refund_transaction_id IS NOT NULL)
OR (transaction_type = 'REFUND' AND refund_transaction_id IS NULL);
Check 5 — Transactions referencing vendors not in the vendor table
SELECT
t.vendor_id,
COUNT(*) AS transaction_count,
SUM(amount_charged) AS gross_amount
FROM transactions t
LEFT JOIN vendors v ON v.vendor_id = t.vendor_id
WHERE v.vendor_id IS NULL
GROUP BY t.vendor_id;
Check 6 — Daily volume spikes per vendor (z-score over a rolling 28-day baseline)
WITH daily AS (
SELECT
vendor_id,
CAST("timestamp" AS DATE) AS day,
COUNT(*) AS txn_count,
SUM(amount_charged) AS gross_amount
FROM transactions
GROUP BY vendor_id, CAST("timestamp" AS DATE)
),
stats AS (
SELECT *,
AVG(txn_count) OVER w AS avg_count,
STDDEV_SAMP(txn_count) OVER w AS sd_count,
AVG(gross_amount) OVER w AS avg_amount,
STDDEV_SAMP(gross_amount) OVER w AS sd_amount,
COUNT(*) OVER w AS baseline_days
FROM daily
WINDOW w AS (
PARTITION BY vendor_id
ORDER BY day
ROWS BETWEEN 28 PRECEDING AND 1 PRECEDING
)
)
SELECT vendor_id, day, txn_count, avg_count, gross_amount, avg_amount
FROM stats
WHERE baseline_days >= 7 -- require at least a week of history
AND sd_count > 0
AND (txn_count - avg_count) / sd_count > 3 -- z-score > 3 on volume
ORDER BY vendor_id, day;
Replace > 3 with a threshold appropriate for the business. Flag on either volume or amount depending on what the team monitors.
Common Mistakes
- Forgetting the date filter before
GROUP BY: aggregating all history and then filtering ranked results is both semantically wrong and slow. - Partitioning only on
city: city names collide across states. - Joining before aggregating: if
vendorshad duplicatevendor_idrows (it shouldn't, but defensive coding matters), the join before aggregation would double-count transactions. - Using
ROW_NUMBERfor ties: silently drops vendors with equal revenue at the boundary. - Treating
amount_chargedas signed in the raw table: the schema stores it as a positive integer; the sign comes fromtransaction_type. Applying-amount_chargedwithout theCASEwould produce wrong results for purchases.