-- 从连接后的表中选择需要的列
SELECT
    -- 选择 customer_tb 表中的 pay_ability 列,该列可能表示客户的支付能力
    c.pay_ability,
    -- 计算逾期比率,使用 AVG 函数结合 CASE WHEN 语句来统计逾期情况
    -- case when l.overdue_days is null then 0 else 1 end 表示如果逾期天数为空,则视为未逾期,记为 0;否则视为逾期,记为 1
    -- AVG(case when l.overdue_days is null then 0 else 1 end) 计算逾期的平均比例
    -- round( 100 * AVG(case when l.overdue_days is null then 0 else 1 end),1) 将逾期比例乘以 100 并保留一位小数
    -- concat(round( 100 * AVG(case when l.overdue_days is null then 0 else 1 end),1), '%') 将计算结果转换为百分比形式
    concat(round( 100 * AVG(case when l.overdue_days is null then 0 else 1 end),1), '%') as overdue_ratio
FROM 
    -- 指定主表为 customer_tb,并使用别名 c
    customer_tb c
    -- 通过 customer_id 列将 customer_tb 表和 loan_tb 表进行内连接
    -- 确保只选择在两个表中都有匹配记录的客户信息
    JOIN loan_tb l
    ON c.customer_id = l.customer_id
-- 按照客户的支付能力进行分组
-- 以便对每个支付能力组内的数据进行聚合计算(如计算逾期比率)
GROUP BY c.pay_ability
-- 按照逾期比率降序排序结果
-- 使逾期比率高的支付能力组排在前面
ORDER BY overdue_ratio DESC;