KatInterview

SQL Net Revenue Rankings and Transaction Data Quality Checks

SQL & DataModel answer
MediumModel answerSQL & Datasqlwindow-functionsdata-quality

Last 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

ColumnTypeDescription
transaction_idintUnique row identifier.
vendor_idintVendor who received or refunded the payment.
amount_chargedintAbsolute dollar amount of the transaction.
transaction_typevarcharEither PURCHASE or REFUND.
refund_transaction_idintFor refunds: the transaction_id of the original purchase. NULL for purchases.
timestampdatetimeWhen the transaction occurred.

Sample data:

transaction_idvendor_idamount_chargedtransaction_typerefund_transaction_idtimestamp
1011200PURCHASEnull2025-01-01
1021150PURCHASEnull2025-01-10
1031200REFUND1012025-01-15
1042300PURCHASEnull2025-02-01
1053500PURCHASEnull2025-03-01

Table: vendors

ColumnTypeDescription
vendor_idintUnique vendor identifier.
cityvarcharVendor's city.
statevarcharVendor's state.
countryvarcharVendor's country.

Sample data:

vendor_idcitystatecountry
1San JoseCAUS
2San JoseCAUS
3AustinTXUS
4SeattleWAUS
5DallasTXUS

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.