-- 企业信用等级分布
CREATE table dim_bank_grade as
SELECT bank_grade as name ,count(*) as value  from tb_banks GROUP BY bank_grade;

-- 还款状态分析
CREATE table dim_loan_status as
SELECT loan_status as name ,count(*) as value  from tb_loans GROUP BY loan_status;

-- 贷款金额变化趋势
CREATE table dim_loan_amount as
SELECT
    loan_date AS date,
		round( SUM(loan_amount) / 10000,2  )AS amount
FROM
    tb_loans
GROUP BY
    loan_date;

-- 企业还款状态分析
CREATE table dim_repayment_status as
SELECT
    repayment_date,
    ROUND(SUM(CASE WHEN repayment_status = '按时还款' THEN repayment_amount ELSE 0 END), 2) AS on_time_amount,
    ROUND(SUM(CASE WHEN repayment_status = '逾期还款' THEN repayment_amount ELSE 0 END), 2) AS overdue_amount,
    ROUND(SUM(repayment_amount), 2) AS total_amount
FROM
    tb_repayments
WHERE
    repayment_status IN ('按时还款', '逾期还款')
GROUP BY
    repayment_date
ORDER BY
    repayment_date;


-- 每年借款数量
CREATE TABLE dim_jie_count as
SELECT
    YEAR(STR_TO_DATE(loan_date, '%Y/%m/%d')) AS name,
    COUNT(*) AS value
FROM
    tb_loans
GROUP BY
    YEAR(STR_TO_DATE(loan_date, '%Y/%m/%d'))
ORDER BY name;
-- 每年逾期占比
CREATE table dim_total_count as
SELECT
    t.year,
    t.loan_status,
    t.status_count,
    ROUND(t.status_count * 100.0 / total.total_count, 2) AS percentage
FROM (
    SELECT
        YEAR(STR_TO_DATE(loan_date, '%Y/%m/%d')) AS year,
        loan_status,
        COUNT(*) AS status_count
    FROM
        tb_loans
    GROUP BY
        YEAR(STR_TO_DATE(loan_date, '%Y/%m/%d')), loan_status
) t
JOIN (
    SELECT
        YEAR(STR_TO_DATE(loan_date, '%Y/%m/%d')) AS year,
        COUNT(*) AS total_count
    FROM
        tb_loans
    GROUP BY
        YEAR(STR_TO_DATE(loan_date, '%Y/%m/%d'))
) total ON t.year = total.year
ORDER BY
    t.year, t.status_count DESC;
