Find the day each user crossed a token quota with a running total
Why it matters Quota alerts, budget burn-down charts and cumulative spend reports all depend on per-user running totals.
Free tiers on LLM apps have a token quota. Support wants to know the exact day each user crossed it, which needs a running total over days, not over single requests.
Write query() returning a SQLite SQL string. Table usage(user_id INTEGER, day TEXT, tokens INTEGER), many rows per user per day, day as 'YYYY-MM-DD'.
The quota is 1000 tokens. For each user, sum tokens per day, then take the running total of those daily sums in day order. Return (user_id, cross_day, total_at_cross) for every user whose running total ever reaches at least 1000, where cross_day is the first day it does and total_at_cross is the running total at the end of that day. Order by user_id ascending.
def query()Example
user 1 uses 600 on 2026-01-01, then 300 and 200 on 2026-01-02; user 2 uses 50 on 2026-01-01. Result: [(1, '2026-01-02', 1100)].
Understand the idea
A running total adds each new value to the sum of everything before it. In SQL, SUM(x) OVER (PARTITION BY user ORDER BY day) computes it: the window for each row is all earlier rows of the same user up to this one.
Worked example: user 1 has daily totals 600 on Jan 1 and 300 + 200 = 500 on Jan 2. Running totals: Jan 1 = 600, Jan 2 = 600 + 500 = 1100. The first day with total >= 1000 is Jan 2, at 1100. User 2 only reaches 50, so they are not listed.
Rule: running_t = sum of daily_s for all days s <= t, per user. Aggregate to the day first so the running total moves in whole days, then filter and take the first matching row with ROW_NUMBER.
Billing systems, quota enforcement and cumulative eval charts all use running totals.