Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top Spending Categories SQL

HardSQL · PostgreSQL00:00
Practice interviewer
In session
5 left
00:00

Your question is Top Spending Categories SQL. Start with the requirements and the three tables on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Brex finance teams need a recent view of company spending by category. Write a PostgreSQL query that finds the top three categories for each company using net spend after refunds, evaluated as of 2025-03-31.

Requirements

  1. Include transactions from the 30-day period from 2025-03-02 through 2025-03-31, inclusive.
  2. Aggregate refunds by transaction before joining them to card transactions, because a transaction may have multiple refunds.
  3. Treat missing refunds as zero and calculate net_spend as transaction amount minus refunded amount.
  4. Aggregate net spend by company and category, then return the top three categories per company using a window function.
  5. Include ties only when they fall within the first three row positions, and sort the final output by company name and descending net spend.

Schema

companies
ColumnTypeDescription
company_idPKINTUnique Brex customer company identifier
company_nameVARCHAR(120)Company display name
card_transactions
ColumnTypeDescription
transaction_idPKINTUnique card transaction identifier
company_idINTCompany associated with the transaction
categoryVARCHAR(80)Spending category
amountNUMERIC(12,2)Original positive transaction amount
transaction_dateDATEDate the transaction posted
refunds
ColumnTypeDescription
refund_idPKINTUnique refund identifier
transaction_idINTTransaction receiving the refund
amountNUMERIC(12,2)Refund amount
refunded_atDATEDate the refund posted
Tablescompaniescard_transactionsrefunds
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results