-- Club ARR at each month's end, by currency -- Twelve times the Club's MRR at the month's end. WITH m AS (SELECT strftime(range, '%Y-%m') AS month, range AS t0, range + INTERVAL 1 MONTH AS t FROM range(TIMESTAMP '2023-10-01', TIMESTAMP '2026-10-01', INTERVAL 1 MONTH)), s AS (SELECT s.subscription_id, s.interval, s.ended_at, upper(p.currency) AS cur FROM billing.subscription s JOIN billing.price p USING (price_id) WHERE NOT s.is_gift), l AS (SELECT i.subscription_id, i.invoice_id, i.created, l.period_start, l.period_end, sum(l.amount - coalesce(l.discount_amount, 0)) AS net FROM billing.invoice i JOIN billing.invoice_line l USING (invoice_id) WHERE i.subscription_id IS NOT NULL AND i.status <> 'void' GROUP BY 1, 2, 3, 4, 5), c AS (SELECT m.month, s.cur, s.subscription_id, CASE WHEN s.interval = 'year' THEN l.net / 12.0 ELSE l.net END / 100.0 AS mrr FROM m JOIN l ON l.period_start < m.t AND l.period_end >= m.t JOIN s ON s.subscription_id = l.subscription_id AND (s.ended_at IS NULL OR s.ended_at >= m.t) QUALIFY row_number() OVER (PARTITION BY m.month, s.subscription_id ORDER BY l.created DESC, l.invoice_id DESC) = 1) SELECT month, cur AS grp, 12 * sum(mrr) AS value FROM c GROUP BY 1, 2 ORDER BY 1, 2