create view vi_overdue_contract as (
SELECT LRP1.CONTRACT_ID                                                                                            AS CONTRACT_ID,
       LRP1.OVERDUE_CORPUS                                                                                         AS OVERDUE_CORPUS,
       (CASE
            WHEN (LRP2.CONTRACT_ID IS NOT NULL) THEN (to_days(date_format(now(), '%Y/%m/%d')) - to_days(date_format(LRP2.PLAN_DATE, '%Y/%m/%d')))
            ELSE (to_days(date_format(now(), '%Y/%m/%d')) - to_days(date_format(LRP3.PLAN_DATE, '%Y/%m/%d'))) END) AS OVERDUE_DAY
FROM ((((
    SELECT LRP.CONTRACT_ID AS CONTRACT_ID, min(LRP.PLAN_LIST) AS PLAN_LIST, (sum(LRP.CORPUS) - sum(ifnull(LRI.CORPUS, 0))) AS OVERDUE_CORPUS
    FROM (APZL.LC_RENT_PLAN LRP
    LEFT JOIN (
        SELECT APZL.LC_RENT_INCOME.CONTRACT_ID AS CONTRACT_ID, APZL.LC_RENT_INCOME.PLAN_LIST AS PLAN_LIST, sum(APZL.LC_RENT_INCOME.CORPUS) AS CORPUS
        FROM APZL.LC_RENT_INCOME
        GROUP BY APZL.LC_RENT_INCOME.CONTRACT_ID, APZL.LC_RENT_INCOME.PLAN_LIST
    ) LRI ON (((LRI.CONTRACT_ID = LRP.CONTRACT_ID) AND (LRI.PLAN_LIST = LRP.PLAN_LIST))))
    WHERE (((LRP.CORPUS - ifnull(LRI.CORPUS, 0)) <> 0) AND
           ((to_days(date_format(now(), '%Y/%m/%d')) - to_days(date_format(LRP.PLAN_DATE, '%Y/%m/%d'))) > 2))
    GROUP BY LRP.CONTRACT_ID
) LRP1 LEFT JOIN (
    SELECT LRI.CONTRACT_ID AS CONTRACT_ID, max((LRI.PLAN_LIST + 1)) AS PLAN_LIST
    FROM ((
              SELECT APZL.LC_RENT_INCOME.CONTRACT_ID    AS CONTRACT_ID,
                     APZL.LC_RENT_INCOME.PLAN_LIST      AS PLAN_LIST,
                     sum(APZL.LC_RENT_INCOME.CORPUS)    AS CORPUS,
                     min(APZL.LC_RENT_INCOME.HIRE_DATE) AS HIRE_DATE
              FROM APZL.LC_RENT_INCOME
              GROUP BY APZL.LC_RENT_INCOME.CONTRACT_ID, APZL.LC_RENT_INCOME.PLAN_LIST
          ) LRI
    LEFT JOIN APZL.LC_RENT_PLAN LRP ON (((LRP.CONTRACT_ID = LRI.CONTRACT_ID) AND (LRP.PLAN_LIST = LRI.PLAN_LIST))))
    WHERE (((to_days(date_format(LRI.HIRE_DATE, '%Y/%m/%d')) - to_days(date_format(LRP.PLAN_DATE, '%Y/%m/%d'))) < 3) AND
           ((LRP.CORPUS - LRI.CORPUS) = 0))
    GROUP BY LRI.CONTRACT_ID
) LRI ON ((LRI.CONTRACT_ID = LRP1.CONTRACT_ID))) LEFT JOIN (
    SELECT APZL.LC_RENT_PLAN.CONTRACT_ID AS CONTRACT_ID, APZL.LC_RENT_PLAN.PLAN_LIST AS PLAN_LIST, max(APZL.LC_RENT_PLAN.PLAN_DATE) AS PLAN_DATE
    FROM APZL.LC_RENT_PLAN
    GROUP BY APZL.LC_RENT_PLAN.CONTRACT_ID, APZL.LC_RENT_PLAN.PLAN_LIST
) LRP2 ON (((LRP2.CONTRACT_ID = LRI.CONTRACT_ID) AND (LRP2.PLAN_LIST = LRI.PLAN_LIST))))
LEFT JOIN (
    SELECT APZL.LC_RENT_PLAN.CONTRACT_ID AS CONTRACT_ID, max(APZL.LC_RENT_PLAN.PLAN_DATE) AS PLAN_DATE
    FROM APZL.LC_RENT_PLAN
    WHERE (APZL.LC_RENT_PLAN.PLAN_LIST = '1')
    GROUP BY APZL.LC_RENT_PLAN.CONTRACT_ID
) LRP3 ON ((LRP3.CONTRACT_ID = LRP1.CONTRACT_ID)))
GROUP BY LRP1.CONTRACT_ID);

-- comment on column vi_overdue_contract.CONTRACT_ID not supported: 合同编号

