Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Rolling Averages and Anomalies

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

Your question is SQL Rolling Averages and Anomalies. 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

S&P Global teams monitor product-level financial metrics across platforms such as Capital IQ and Market Intelligence. Write a PostgreSQL query that calculates a trailing three-observation average and flags unusually large fluctuations.

Requirements

  1. Join financial_metrics to spg_products and include only active products with non-null metric values.
  2. Calculate the average of the three preceding observations for each product, ordered by metric_date.
  3. Flag a row as anomalous when its metric differs from the trailing average by more than 20 percent. Rows without three preceding observations are not anomalous.
  4. Return the product name, date, metric value, rounded trailing average, and anomaly flag in chronological order per product.

Schema

spg_products
ColumnTypeDescription
product_idPKINTUnique product identifier
product_nameVARCHAR(100)S&P Global product name
is_activeBOOLEANWhether the product is monitored
financial_metrics
ColumnTypeDescription
metric_idPKINTUnique metric observation identifier
product_idINTReferenced product identifier
metric_dateDATEDate of the observation
metric_valueDECIMAL(14,2)Observed financial metric value
Tablesspg_productsfinancial_metrics
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results