SQL120 贷款情况
SQL120 贷款情况
withcity_loan_stats as (selectcity,sum(loan_amount) as total_loan_amount,round(sum(loan_amount) / count(distinct customer_id), 2) as average_loan_amount,count(distinct customer_id) as total_customersfromloan_applicationsjoin customers using (customer_id)group bycity),popular_loan_types as (selectcity,loan_type_name as most_applied_loan_typefrom(selectcity,loan_type_name,loan_type_id,row_number() over (partition bycityorder bycount(*) desc,loan_type_id asc) as rkfromloan_applicationsjoin customers using (customer_id)join (select distinctapplication_id,loan_type_name,loan_types.loan_type_idfromloan_typesjoin loan_application_types using (loan_type_id)) as t1 using (application_id)group bycity,loan_type_name,loan_type_id) as t2whererk = 1)
select*
fromcity_loan_statsjoin popular_loan_types using (city)
order bycity
SQL查询分析
这个查询的目的是分析各城市的贷款申请数据,主要关注三个方面的指标:贷款总额、客户平均贷款额,以及最受欢迎的贷款类型。
1. 整体结构
查询使用了两个CTE(Common Table Expressions):
city_loan_stats
:计算城市级别的贷款汇总统计popular_loan_types
:找出每个城市最受欢迎的贷款类型
最后将这两个CTE通过城市(city)关联,输出完整的分析结果。
2. 第一个CTE:city_loan_stats
SELECTcity,SUM(loan_amount) AS total_loan_amount,ROUND(SUM(loan_amount) / COUNT(DISTINCT customer_id), 2) AS avg_loan_per_customer,COUNT(DISTINCT customer_id) AS customer_count
FROMloan_applicationsJOIN customers USING (customer_id)
GROUP BYcity
功能:
- 计算每个城市的总贷款金额(
total_loan_amount
) - 计算每个客户的平均贷款金额(
avg_loan_per_customer
) - 统计每个城市的客户数量(
customer_count
)
实现方式:
- 通过
JOIN
连接loan_applications
和customers
表 - 按城市(
city
)分组 - 使用聚合函数计算各项指标
3. 第二个CTE:popular_loan_types
SELECTcity,loan_type_name AS most_popular_loan_type
FROM(SELECTcity,loan_type_name,loan_type_id,ROW_NUMBER() OVER (PARTITION BY cityORDER BY COUNT(*) DESC, loan_type_id ASC) AS rankFROMloan_applicationsJOIN customers USING (customer_id)JOIN (SELECT DISTINCTapplication_id,loan_type_name,loan_types.loan_type_idFROMloan_typesJOIN loan_application_types USING (loan_type_id)) AS loan_type_data USING (application_id)GROUP BYcity,loan_type_name,loan_type_id) AS ranked_loans
WHERErank = 1
功能:
- 找出每个城市申请次数最多的贷款类型
实现方式:
- 通过多层连接获取完整的贷款申请数据(包括城市和贷款类型信息)
- 按城市和贷款类型分组统计申请次数
- 使用窗口函数
ROW_NUMBER()
为每个城市的贷款类型按申请次数排序PARTITION BY city
:按城市分区ORDER BY COUNT(*) DESC
:按申请次数降序loan_type_id ASC
:次数相同时按loan_type_id升序(作为tie-breaker)
- 筛选出排名第一的记录(rank = 1)
4. 最终查询
SELECTcls.city,cls.total_loan_amount,cls.avg_loan_per_customer,cls.customer_count,plt.most_popular_loan_type
FROMcity_loan_stats clsJOIN popular_loan_types plt USING (city)
ORDER BYcls.city
功能:
- 将两个CTE的结果按城市关联
- 输出完整的城市贷款分析报告
- 按城市名称排序
5. 业务价值
这个查询提供了以下业务洞察:
- 城市贷款规模:通过总贷款金额了解哪些城市贷款业务量大
- 客户价值:通过平均贷款金额了解不同城市客户的贷款规模
- 客户基础:通过客户数量了解各城市市场渗透率
- 产品偏好:了解不同城市客户最青睐的贷款产品类型