Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Month-Over-Month Revenue and Gross Profit

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

Your question is SQL Month-Over-Month Revenue and Gross Profit. 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

Advance Business Capital's Operations team needs a monthly store performance view. Write a PostgreSQL query that calculates revenue, gross profit, and month-over-month changes for each store using qualifying transactions from January through March 2024.

Requirements

  1. Aggregate transactions by store and calendar month.
  2. Calculate gross profit as revenue minus cost. Treat a NULL cost as zero.
  3. Use a window function to compare each store's month with its previous available month. Return NULL changes for the first month.
  4. Exclude transactions outside the reporting period and transactions that do not match a known store. Sort by store ID and month.

Representative Data

store_transactions includes multiple transactions per store-month, a zero-revenue month, a NULL cost, an unmatched store, and a transaction outside the reporting period.

Schema

stores
ColumnTypeDescription
store_idPKINTEGERUnique store identifier
store_nameVARCHAR(100)Store display name
store_transactions
ColumnTypeDescription
transaction_idPKINTEGERUnique transaction identifier
store_idINTEGERReferenced store identifier
transaction_dateDATEDate the transaction occurred
revenueNUMERIC(12,2)Revenue generated by the transaction
costNUMERIC(12,2)Transaction cost
Tablesstoresstore_transactions
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results