Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Top Spending by Month

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

Your question is SQL Top Spending by Month. Start with the requirements and the two 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

Booz Allen Hamilton's Data Science practice needs a monthly view of spending by department. Write a PostgreSQL query that returns the three highest-spending departments for each calendar month.

Requirements

  1. Include only transactions with status = 'completed' and a positive amount.
  2. Join transactions to departments so orphaned department IDs are excluded.
  3. Aggregate spending by calendar month and department, then rank departments independently within each month.
  4. Return the top three departments per month, ordered by month ascending and spending descending. Break equal-spending ties alphabetically by department name.

Schema

departments
ColumnTypeDescription
department_idPKINTUnique department identifier
department_nameVARCHAR(100)Department display name
transactions
ColumnTypeDescription
transaction_idPKINTUnique transaction identifier
department_idINTDepartment associated with the transaction
transaction_dateDATEDate on which the transaction occurred
amountNUMERIC(12,2)Transaction amount in dollars
statusVARCHAR(20)Transaction processing status
Tablesdepartmentstransactions
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results