# 之后做法可以考虑，不写复杂的sql，先把基础数据从数据库导出来（csv文件），然后用程序来处理（过滤、转换、连接等），这样速度可能会快一点
# 要不然每次都查询一次全量数据，很费时，发现sql错了，又得重新导一下数据
# 放款还款计划表
SELECT
  t3.class,
  date_format(t2.loan_paid_at, '%Y-%m') loan_month,
  t2.loan_paid_at,
  t2.ref_id,
  t2.loan_id,
  t2.service_fee1                       total_req_service_fee1,
  t2.service_fee1 / t2.contract_term    loan_req_service_fee1,
  t2.is_active,
  t2.funding_code,
  date_format(t1.deadline, '%Y-%m')     plan_month,
  t1.deadline,
  t1.term_no,
  t1.id                                 plan_id,
  t1.service_fee1                       plan_req_service_fee1,
  t1.service_fee2                       plan_req_service_fee2
FROM
  temp.user_repayment_plan t1
  JOIN temp.loan_manifest t2
    ON t1.ref_id = t2.ref_id
       AND t2.loan_paid_at < '2017-01-01 00:00:00'
  JOIN temp.loan_class t3 ON t3.ref_id = t2.ref_id;

# 非新马上还款计划表
SELECT
  date_format(t2.repaid_at, '%Y-%m') repay_month,
  t2.repaid_at,
  t1.plan_id,
  t1.service_fee1                    real_service_fee1,
  t1.service_fee2                    real_service_fee2,
  t1.mitigate_service_fee
FROM
  temp.xjd_repay_plan_repay_record_ref t1
  JOIN temp.xjd_repay_plan_repay_record_ref_repay_date t2
    ON t1.id = t2.xjd_ref_id AND t2.repaid_at < '2017-01-01 00:00:00'
  JOIN temp.user_repayment_plan t3 ON t3.id = t1.plan_id AND t3.fund_code <> 160;

# 新马上
SELECT
  date_format(t1.repaid_at, '%Y-%m') repay_month,
  t1.repaid_at,
  t2.id                                plan_id,
  t1.service_fee1                      real_service_fee1,
  t1.service_fee2                      real_service_fee2,
  0                                    mitigate_service_fee
FROM temp.new_ms_transaction_with_term_copy t1
  JOIN temp.user_repayment_plan t2 ON t2.real_loan_id = t1.loan_id
                                      AND t2.term_no = t1.term_no AND t2.fund_code = 160 AND
                                      t1.repaid_at < '2017-01-01 00:00:00';
