Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top 5% Energy Spike Users

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

Your question is Top 5% Energy Spike Users. 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

Bidgely's energy analytics platform needs to identify customers whose consumption varies sharply from their typical usage. Write a PostgreSQL query using common table expressions to find the top 5% of users by energy spike score.

Define a user's energy spike score as their maximum recorded usage_kwh minus their average non-null usage_kwh during the analysis period. Users without valid usage readings should not be ranked.

Requirements

  1. Aggregate each user's maximum usage, average usage, and spike score.
  2. Use a CTE to calculate the 95th percentile spike-score threshold with PERCENTILE_CONT.
  3. Return users whose score is greater than or equal to that threshold, ordered from highest to lowest score.
  4. Include the user's region and the number of valid readings.

Schema

users
ColumnTypeDescription
user_idPKINTEGERUnique customer identifier
user_nameVARCHAR(100)Customer name
regionVARCHAR(50)Customer service region
energy_usage
ColumnTypeDescription
usage_idPKINTEGERUnique energy usage reading identifier
user_idINTEGERReferences users.user_id
reading_dateDATEDate of the energy reading
usage_kwhNUMERIC(10,2)Energy consumed in kilowatt-hours
Tablesusersenergy_usage
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results