-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalysis_queries.sql
More file actions
59 lines (55 loc) · 1.73 KB
/
analysis_queries.sql
File metadata and controls
59 lines (55 loc) · 1.73 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
-- 1. Total loans issued by loan type
SELECT loan_type,
COUNT(*) AS total_loans,
SUM(loan_amount) AS total_amount
FROM loans
WHERE loan_status = 'Approved'
GROUP BY loan_type;
-- 2. Average income for approved vs rejected loans
SELECT l.loan_status,
AVG(c.income) AS avg_income
FROM loans l
JOIN customers c ON l.customer_id = c.customer_id
GROUP BY l.loan_status;
-- 3. Default rate by loan type
SELECT l.loan_type,
COUNT(*) AS total_loans,
SUM(r.default_flag) AS defaults,
ROUND(SUM(r.default_flag) * 100.0 / COUNT(*), 2) AS default_rate_pct
FROM loans l
JOIN repayments r ON l.loan_id = r.loan_id
GROUP BY l.loan_type;
-- 4. Customer risk segmentation
SELECT customer_id,
credit_score,
income,
CASE
WHEN credit_score < 600 THEN 'High Risk'
WHEN credit_score BETWEEN 600 AND 700 THEN 'Medium Risk'
ELSE 'Low Risk'
END AS risk_category
FROM customers;
-- 5. High-risk customers: more than 1 loan and at least 1 default
WITH customer_loan_summary AS (
SELECT
c.customer_id,
COUNT(l.loan_id) AS total_loans,
SUM(COALESCE(r.default_flag, 0)) AS total_defaults,
AVG(c.credit_score) AS avg_credit_score
FROM customers c
JOIN loans l ON c.customer_id = l.customer_id
LEFT JOIN repayments r ON l.loan_id = r.loan_id
GROUP BY c.customer_id
)
SELECT
customer_id,
total_loans,
total_defaults,
CASE
WHEN avg_credit_score < 600 THEN 'High Risk'
WHEN avg_credit_score BETWEEN 600 AND 700 THEN 'Medium Risk'
ELSE 'Low Risk'
END AS risk_category
FROM customer_loan_summary
WHERE total_loans > 1
AND total_defaults >= 1;