-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfraud_analysis.sql
More file actions
87 lines (79 loc) · 2.15 KB
/
Copy pathfraud_analysis.sql
File metadata and controls
87 lines (79 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
-- These queries run against a DuckDB view named transactions.
-- query: total_transactions
SELECT
COUNT(*) AS transactions,
SUM(isFraud) AS fraud_transactions,
COUNT(*) - SUM(isFraud) AS non_fraud_transactions,
AVG(isFraud) AS fraud_rate
FROM transactions;
-- query: fraud_by_type
SELECT
type,
COUNT(*) AS transactions,
SUM(isFraud) AS fraud_transactions,
AVG(isFraud) AS fraud_rate,
SUM(CASE WHEN isFraud = 1 THEN amount ELSE 0 END) AS fraud_amount
FROM transactions
GROUP BY type
ORDER BY fraud_rate DESC;
-- query: fraud_amount_by_type
SELECT
type,
SUM(CASE WHEN isFraud = 1 THEN amount ELSE 0 END) AS fraud_amount,
AVG(CASE WHEN isFraud = 1 THEN amount END) AS average_fraud_amount,
MAX(CASE WHEN isFraud = 1 THEN amount END) AS maximum_fraud_amount
FROM transactions
GROUP BY type
ORDER BY fraud_amount DESC;
-- query: fraud_by_hour
SELECT
MOD(step, 24) AS hour,
COUNT(*) AS transactions,
SUM(isFraud) AS fraud_transactions,
AVG(isFraud) AS fraud_rate
FROM transactions
GROUP BY hour
ORDER BY hour;
-- query: fraud_by_day
SELECT
CAST(step / 24 AS INTEGER) AS day,
COUNT(*) AS transactions,
SUM(isFraud) AS fraud_transactions,
AVG(isFraud) AS fraud_rate
FROM transactions
GROUP BY day
ORDER BY day;
-- query: fraud_by_amount_band
SELECT
CASE
WHEN amount < 1000 THEN '<1k'
WHEN amount < 10000 THEN '1k-10k'
WHEN amount < 100000 THEN '10k-100k'
WHEN amount < 1000000 THEN '100k-1m'
ELSE '>=1m'
END AS amount_band,
COUNT(*) AS transactions,
SUM(isFraud) AS fraud_transactions,
AVG(isFraud) AS fraud_rate
FROM transactions
GROUP BY amount_band
ORDER BY MIN(amount);
-- query: high_risk_segments
SELECT
type,
MOD(step, 24) AS hour,
COUNT(*) AS transactions,
SUM(isFraud) AS fraud_transactions,
AVG(isFraud) AS fraud_rate
FROM transactions
GROUP BY type, hour
HAVING COUNT(*) >= 1000
ORDER BY fraud_rate DESC
LIMIT 20;
-- query: alert_volume
SELECT
COUNT(*) AS scored_transactions,
SUM(fraud_flag) AS alerts,
AVG(CAST(fraud_flag AS INTEGER)) AS alert_rate,
AVG(fraud_score) AS mean_fraud_score
FROM predictions;