SQL

Detección de fraude: transacciones multipaís muy próximas en la misma tarjeta

Una ventana LAG por tarjeta compara cada transacción con la anterior: un cambio de país en menos de una hora es físicamente imposible — señal clásica de tarjeta comprometida.

Requisitos

PostgreSQL, SQL Server, MySQL 8+ (LAG + WINDOW)

SQL
WITH suivi AS (
    SELECT card_id, tx_id, tx_time, country, amount,
           LAG(country) OVER w AS pays_prec,
           LAG(tx_time) OVER w AS heure_prec
    FROM transactions
    WHERE tx_time >= now() - interval '24 hours'
    WINDOW w AS (PARTITION BY card_id ORDER BY tx_time)
)
SELECT
    card_id,
    tx_id,
    pays_prec || ' → ' || country AS saut_pays,
    to_char(tx_time - heure_prec, 'HH24:MI:SS') AS ecart,
    amount
FROM suivi
WHERE country <> pays_prec
  AND tx_time - heure_prec < interval '1 hour'
ORDER BY tx_time - heure_prec;

Resultado

   card_id    | tx_id  | saut_pays |  ecart   | amount
--------------+--------+-----------+----------+--------
 4970...8821  | 991204 | FR → BR   | 00:04:12 | 890.00
 4970...8821  | 991388 | BR → FR   | 00:18:40 | 120.50
 5312...0476  | 990817 | DE → TH   | 00:31:05 | 449.99
 4539...6610  | 991472 | ES → US   | 00:52:48 |  75.00
(4 rows)

Carte 4970...8821 : aller-retour FR/BR en 23 min — blocage immédiat recommandé
SQLFraudeLAGWindow FunctionsSécurité

Snippets relacionados

Volver al Data Lab