-- [params]
-- date :start_date
-- date :end_date
WITH token_usage AS (
SELECT
user_id,
SUM(request_tokens) AS total_request_tokens,
SUM(response_tokens) AS total_response_tokens,
SUM(request_tokens + response_tokens) AS total_tokens
FROM
ai_api_audit_logs
WHERE
created_at BETWEEN :start_date AND :end_date
GROUP BY
user_id
)
SELECT
u.id user_id,
tu.total_request_tokens,
tu.total_response_tokens,
tu.total_tokens
FROM
token_usage tu
JOIN
users u ON u.id = tu.user_id
ORDER BY
tu.total_tokens DESC
Will show top usage per user for date range.