Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Token Consumption Moving Averages

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

Your question is Token Consumption Moving Averages. 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

Anthropic needs a daily view of token consumption for enterprise accounts using the Claude API. Write a PostgreSQL query that aggregates usage events and calculates both short-term usage trends and cumulative consumption.

Requirements

  1. Include only accounts where account_type = 'enterprise' and status = 'active'.
  2. Aggregate multiple token usage events for the same account and date into daily_tokens. Treat NULL token counts as zero.
  3. Calculate a three-row moving average, including the current day and up to the two preceding observed usage days for that account.
  4. Calculate a cumulative token total for each account in chronological order, and sort the final output by account name and usage date.

Schema

enterprise_accounts
ColumnTypeDescription
account_idPKINTEGERUnique enterprise account identifier
account_nameVARCHAR(100)Enterprise customer name
account_typeVARCHAR(30)Customer segment
statusVARCHAR(20)Account lifecycle status
token_usage
ColumnTypeDescription
usage_idPKBIGINTUnique token usage event identifier
account_idINTEGERReferences enterprise_accounts.account_id
usage_dateDATEUTC calendar date of token usage
token_countBIGINTTokens consumed in the event
Tablesenterprise_accountstoken_usage
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results