Compute day-over-day percent change in API cost per team with LAG

HardSQLPro

A cost spike alert compares each team's spend today with its previous recorded day. The raw log has many requests per day, so you must total first and compare second.

Write query() returning a SQLite SQL string. Table requests(team TEXT, day TEXT, cost REAL), many rows per team per day; day is 'YYYY-MM-DD'.

Return one row per (team, day) that appears: (team, day, total, pct_change).
- total is ROUND(SUM(cost), 2) for that team and day.
- pct_change is ROUND(100.0 * (total - prev) / prev, 1) where prev is the unrounded total of the same team on its previous recorded day (days with no rows are skipped, not treated as 0).
- pct_change is NULL for a team's first day, and NULL when prev is 0.

Order by team ascending, then day ascending.

Signaturedef query()

Example

team 'a' has 2.0 + 2.0 on 2026-01-01 and 5.0 on 2026-01-03. Result: [('a', '2026-01-01', 4.0, None), ('a', '2026-01-03', 5.0, 25.0)].

Understand the idea

To compare a team's spend with its previous day, first turn many request rows into one total per team per day, then look one row back within the same team. Days with no rows are simply absent, so 'previous' means the previous recorded day, not the calendar day before. Worked example for team b: day 1 has 1.5 + 2.5 = 4.0, day 2 has 6.0, day 4 has 3.0. Day 1 has no previous, so NULL. Day 2: 100 * (6 - 4) / 4 = 50.0. Day 4 compares with day 2: 100 * (3 - 6) / 6 = -50.0. If a previous total were 0, the change would be NULL rather than a division error. Rule in words: in a first step, group by team and day and sum cost; in a second step, use LAG over the team's days ordered by date to get prev; output ROUND(total, 2) and ROUND(100.0 * (total - prev) / prev, 1), with NULLIF on prev so 0 gives NULL. Use the unrounded total as prev. Sort by team then day. Used for cost spike alerts on LLM spend.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: example_run1(query())
  • Sample 2: two teams interleaved_run2(query())