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
- Include transactions from the 30-day period from 2025-03-02 through 2025-03-31, inclusive.
- Aggregate refunds by transaction before joining them to card transactions, because a transaction may have multiple refunds.
- Treat missing refunds as zero and calculate
net_spend as transaction amount minus refunded amount.
- Aggregate net spend by company and category, then return the top three categories per company using a window function.
- Include ties only when they fall within the first three row positions, and sort the final output by company name and descending net spend.
Output details
- Return columns in this order:
company_name, category, net_spend, and category_rank.
- Filter refunds from
2025-03-02 inclusive through 2025-04-01 exclusive.
- Replace a NULL
category with Uncategorized.
- Break equal
net_spend values by ascending category when assigning ranks.
- Sort the final rows by ascending
company_name, then ascending category_rank.
- Do not round
net_spend; retain the numeric precision produced by the calculations.