Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Rolling GM% With Late-Arriving Facts

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

Your question is Rolling GM% With Late-Arriving Facts. 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

NVIDIA finance analysts need a daily gross-margin view for NVIDIA products by sales region. Write a PostgreSQL query using fact_sales and dim_calendar to calculate a 28-day rolling GM% that remains correct when a sale arrives late or a previously loaded sale is corrected.

Requirements

  1. Treat the row with the greatest loaded_at as the current version of each sale_id.
  2. Use dim_calendar as the reporting date spine, including dates with no sales.
  3. Aggregate revenue and COGS by calendar date, region, and product before applying the rolling calculation.
  4. Calculate rolling revenue, rolling COGS, and gm_percent = (revenue - cogs) / revenue * 100, rounded to two decimals.
  5. Return results for every region and product represented by a valid sale, ordered by region, product, and calendar date.

Schema

fact_sales
ColumnTypeDescription
sale_idBIGINTBusiness identifier shared by all versions of a sale
sale_dateDATEEconomic date of the sale, related to dim_calendar.calendar_date
loaded_atTIMESTAMPTimestamp when this fact version entered the warehouse
regionVARCHAR(40)Sales region
productVARCHAR(80)NVIDIA product family
revenueNUMERIC(14,2)Sale revenue
cogsNUMERIC(14,2)Cost of goods sold
dim_calendar
ColumnTypeDescription
calendar_datePKDATECalendar date used as the reporting date spine
Tablesfact_salesdim_calendar
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results