WITH stats_par_ville AS (
SELECT
l.city as ville,
l.country as pays,
COUNT(*) as nb_transactions,
COUNT(DISTINCT t.customer_id) as nb_comptes,
ROUND(AVG(t.amount)::numeric, 2) as montant_moyen,
COUNT(DISTINCT t.ip_address) as nb_ips,
ROUND(COUNT(*)::numeric / NULLIF(COUNT(DISTINCT t.customer_id), 0), 1) as ratio_tx_compte,
ROUND(COUNT(DISTINCT t.ip_address)::numeric / NULLIF(COUNT(DISTINCT t.customer_id), 0), 1) as ratio_ip_compte
FROM transactions t
JOIN locations l ON t.ip_address LIKE l.ip_range || '%'
WHERE t.transaction_date >= '2024-03-15'
GROUP BY l.city, l.country
HAVING COUNT(*) > 0
)
SELECT
ville,
pays,
nb_transactions as "nombre de transactions",
nb_comptes as "nombre de comptes",
montant_moyen as "montant moyen",
nb_ips as "nombre d'IPs",
ratio_tx_compte as "transactions par compte",
ratio_ip_compte as "ip par compte",
( -- Score basé sur le montant
CASE WHEN montant_moyen > 2000 THEN 40
WHEN montant_moyen > 1000 THEN 20
ELSE 0
END +
-- Score basé sur les transactions par compte
CASE WHEN ratio_tx_compte > 8 THEN 15
WHEN ratio_tx_compte > 2 THEN 5
ELSE 0
END +
-- Score basé sur les IPs par compte
CASE WHEN ratio_ip_compte > 3 THEN 30
WHEN ratio_ip_compte > 1 THEN 5
ELSE 0
END
) as score_risque
FROM stats_par_ville
ORDER BY score_risque DESC;