-- Aggregate company stats -- name: UpdateCompanyStats :exec INSERT INTO company_stats ( company_id, total_bets, total_cash_made, total_cash_backs, updated_at ) SELECT b.company_id, COUNT(*) AS total_bets, COALESCE(SUM(b.amount), 0) AS total_cash_made, COALESCE( SUM( CASE WHEN sb.cashed_out THEN b.amount -- use actual cashed_out flag from shop_bets ELSE 0 END ), 0 ) AS total_cash_out, COALESCE( SUM( CASE WHEN b.status = 5 THEN b.amount ELSE 0 END ), 0 ) AS total_cash_backs, NOW() AS updated_at FROM shop_bet_detail b JOIN companies c ON b.company_id = c.id JOIN shop_bets sb ON sb.id = b.id -- join to get cashed_out GROUP BY b.company_id, c.name ON CONFLICT (company_id) DO UPDATE SET total_bets = EXCLUDED.total_bets, total_cash_made = EXCLUDED.total_cash_made, total_cash_out = EXCLUDED.total_cash_out, total_cash_back = EXCLUDED.total_cash_back, updated_at = EXCLUDED.updated_at;