-- Aggregate bet stats per event -- name: UpdateEventBetStats :exec INSERT INTO event_bet_stats ( event_id, number_of_bets, total_amount, avg_bet_amount, total_potential_winnings, updated_at ) SELECT bo.event_id, COUNT(DISTINCT b.id) AS number_of_bets, COALESCE(SUM(b.amount), 0) AS total_amount, COALESCE(AVG(b.amount), 0) AS avg_bet_amount, COALESCE(SUM(b.potential_win), 0) AS total_potential_winnings, NOW() AS updated_at FROM bet_outcomes bo JOIN bets b ON bo.bet_id = b.id GROUP BY bo.event_id ON CONFLICT (event_id) DO UPDATE SET number_of_bets = EXCLUDED.number_of_bets, total_amount = EXCLUDED.total_amount, avg_bet_amount = EXCLUDED.avg_bet_amount, total_potential_winnings = EXCLUDED.total_potential_winnings, updated_at = EXCLUDED.updated_at;