题解 | 贷款情况

贷款情况

https://www.nowcoder.com/practice/2817d353f0634208bcf0de74f56ca8f0

with a as (
    select city, 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_customers
    from loan_applications join loan_application_types using(application_id) join customers using(customer_id) join loan_types using(loan_type_id)
    group by city
),
b as (
    select city, loan_type_id, loan_type_name, count(loan_type_name) over(partition by city) as cnt 
    from loan_applications join loan_application_types using(application_id) join customers using(customer_id) join loan_types using(loan_type_id)
),
c as (
    select city, loan_type_id, loan_type_name, rank() over(partition by city order by cnt desc, loan_type_id) as rnk
    from b 
)
select distinct city, total_loan_amount, average_loan_amount, total_customers, loan_type_name as most_applied_loan_type
from a join c using(city)
where rnk = 1
order by city

首先平均贷款的数量是要按照distinct customer_id来计算,直接group by city然后average会有问题。其次是每个城市最多的贷款金额还是有点麻烦,我先用窗口函数计算数量(groupby当然也行),然后用窗口函数排序。还是比较麻烦的。这种题先把简单的列算出来,难的列放在后面写,再join

全部评论

相关推荐

08-25 22:17
门头沟学院 Java
码农索隆:不用想,这肯定是看谁报道的早了。 而且提前实习,最后很容易被压薪资,轻易别去
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务