Given a table of user receipt scans, write a query to find the top three brand partners by total spend for each user segment over the last quarter at Fetch.
Assume the last quarter is the completed calendar quarter relative to the current date. Exclude scans that cannot be associated with a user segment or brand partner.
Output
- One row per qualifying segment and brand partner, with columns
segment, brand_name, total_spend, and segment_rank.
- Include no more than three brands per segment, ordered by segment, rank, total spend descending, and brand name ascending.
Output details
- Treat
DATE '2026-09-15' as today's date.
- Use an inclusive start and exclusive end for the completed quarter.
- Exclude scans with
spend_amount equal to NULL, while retaining zero and negative amounts.
- Break equal
total_spend values by brand_name ascending when assigning segment_rank.