Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Get started
Compare Week-over-Week with SQL
00:00
5 left

Compare Week-over-Week with SQL

MediumSQL · PostgreSQL

Problem

Write a SQL query to compare current-week and previous-week performance for a product metric using window functions.

Use the products and product_metrics tables. Treat the latest week present in the data as the current week and compare it with the immediately preceding calendar week.

Output

  1. One row per product with metric data in the current week
  2. Columns: product_id, product_name, current_week_metric, previous_week_metric, metric_change, and percentage_change
  3. Return NULL when a previous-week value is unavailable or when percentage change cannot be calculated
  4. Order by product_id ascending

Output details

  • Aggregate each product’s measurements within each week using SUM(metric_value).
  • Treat weeks as Monday-starting calendar weeks.
  • Define metric_change as current value minus previous value.
  • Calculate percentage_change as 100 times metric_change divided by the previous value, rounded to 2 decimal places.
  • Return NULL for percentage_change when the previous value is 0.
  • Preserve NULL when all measurements contributing to a weekly sum are NULL.

Schema

products
ColumnTypeDescription
product_idPKINTUnique product identifier
product_nameVARCHAR(100)Product name
product_metrics
ColumnTypeDescription
metric_idPKINTUnique metric observation identifier
product_idINTReferenced product identifier
measured_atTIMESTAMPTimestamp when the metric was recorded
metric_valueDECIMAL(12,2)Observed product metric value
Tablesproductsproduct_metrics
Interviewer

Whenever you're ready, walk me through your approach or go straight to the code. The requirements and the two tables are in the Question tab.

You need to log in / sign up to run or submit.
CodePostgreSQL
Sign up free to run your codeLog inLn 1
Run your query to see results here.