题解 | 贷款情况

贷款情况

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

-- 做这种题最笨的方法但是最通用的就是,一个指标一个子查询,注意,首列是每一个子查询最终结果的group by 条件


with tla as(
select city,sum(loan_amount) as total_loan_amount
from 
(
select
    la.application_id,
    la.customer_id,
    la.loan_amount,
    cr.city
from
    loan_applications as la 
left join
    customers as cr on la.customer_id = cr.customer_id
) as A
group by city)
,

ala as(
select city,round(sum(loan_amount)/count(distinct customer_id),2) as average_loan_amount
from 
(
select
    la.application_id,
    la.customer_id,
    la.loan_amount,
    cr.city
from
    loan_applications as la 
left join
    customers as cr on la.customer_id = cr.customer_id
) as A
group by city
),

tc as (
select city,count(distinct customer_id) as total_customers
from 
(
select
    la.application_id,
    la.customer_id,
    la.loan_amount,
    cr.city
from
    loan_applications as la 
left join
    customers as cr on la.customer_id = cr.customer_id
) as A
group by city)
,

malt as (
select city,loan_type_name as most_applied_loan_type from 
(
select city,
loan_type_name,
row_number() 
over(partition by city order by counting desc,loan_type_id asc) 
as ranking
from 
(
select city,loan_type_name,loan_type_id,count(loan_type_name) as counting
from 
(
select
    la.application_id,
    la.customer_id,
    la.loan_amount,
    cr.city,
    lt.loan_type_name,
    lt.loan_type_id
from
    loan_applications as la 
left join
    customers as cr on la.customer_id = cr.customer_id
left join 
    loan_application_types as lat on la.application_id = lat.application_id
left join 
    loan_types as lt on lat.loan_type_id = lt.loan_type_id
) as A
group by city,loan_type_name,loan_type_id
) as A
) as A 
where ranking = 1)

select 
tla.city,
tla.total_loan_amount,
ala.average_loan_amount,
tc.total_customers,
malt.most_applied_loan_type
from tla 
left join ala on tla.city = ala.city
left join tc on tla.city = tc.city
left join malt on tla.city = malt.city
order by tla.city

全部评论

相关推荐

在改简历的大卫很认真:天天有面试 = 你已经在 offer 门口了。 海投能面成这样,说明你的简历、基础、学历都是过关的,缺的只是一次刚好匹配的缘分。 关于你说的 SQL 恐惧,我帮你捋一下: - 面试里考来考去,真就那几类: 分组、去重、关联、子查询、窗口函数(row_number、rank、sum 开窗) ​ - 面试官要的不是“写得花里胡哨”,而是思路稳、不出错。 你恐惧的本质不是不会, 是怕临场卡壳、怕写错、怕被追问。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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