with customer_overdue as(
    select
        ct.pay_ability,
        count(distinct ct.customer_id) as overdue_count
    from
        customer_tb ct
    join
        loan_tb lt on ct.customer_id=lt.customer_id
    where
        lt.overdue_days > 0
    group by
        ct.pay_ability
),
customer_total as(
    select
        pay_ability,
        count(distinct customer_id) as total_count
    from
        customer_tb
    group by
        pay_ability
)
select
    ct.pay_ability,
    concat(round(coalesce(co.overdue_count/ct.total_count,0)*100,1),'%') as overdue_ratio
from
    customer_total ct
left join
    customer_overdue co on ct.pay_ability=co.pay_ability
order by
    (coalesce(co.overdue_count/ct.total_count,0)) desc;
  1. CTE(公共表表达式)部分:customer_overdue:这是一个 CTE,用于统计每个支付能力分组下逾期客户的数量。它从customer_tb表和loan_tb表通过customer_id连接,筛选出overdue_days大于 0 的记录,然后按pay_ability分组,统计每个分组下不同customer_id的数量,命名为overdue_count。customer_total:这也是一个 CTE,用于统计每个支付能力分组下的客户总数。它从customer_tb表按pay_ability分组,统计每个分组下不同customer_id的数量,命名为total_count。
  2. 主查询部分:从customer_total表(别名为ct)和customer_overdue表(别名为co)通过pay_ability进行左连接。选择ct.pay_ability和计算逾期比例。逾期比例的计算方式是co.overdue_count除以ct.total_count,如果结果为 NULL 则用 0 代替,然后乘以 100 并保留一位小数,再转换为字符串并加上百分号,命名为overdue_ratio。最后按逾期比例(coalesce(co.overdue_count/ct.total_count,0))降序排列。