SELECT t0.product_no,
SUM(CASE WHEN t0.loan_age = '0未到期' THEN t0.amount ELSE 0 END) AS '0',
SUM(CASE WHEN t0.loan_age = '1-30' THEN t0.amount ELSE 0 END) AS '1-30',
SUM(CASE WHEN t0.loan_age = '31-60' THEN t0.amount ELSE 0 END) AS '31-60',
SUM(CASE WHEN t0.loan_age = '61-90' THEN t0.amount ELSE 0 END) AS '61-90',
SUM(CASE WHEN t0.loan_age = '91-120' THEN t0.amount ELSE 0 END) AS '91-120',
SUM(CASE WHEN t0.loan_age = '121-150' THEN t0.amount ELSE 0 END) AS '121-150',
SUM(CASE WHEN t0.loan_age = '151-180' THEN t0.amount ELSE 0 END) AS '151-180',
SUM(CASE WHEN t0.loan_age = '181-360' THEN t0.amount ELSE 0 END) AS '181-360',
SUM(CASE WHEN t0.loan_age = 'over 360' THEN t0.amount ELSE 0 END) AS '361+'
 FROM (
SELECT u.product_no,IF((DATEDIFF('2017-1-1',u.deadline))>360,'over 360',IF((DATEDIFF('2017-1-1',u.deadline))>180,'181-360',
IF((DATEDIFF('2017-1-1',u.deadline))>150,'151-180',IF((DATEDIFF('2017-1-1',u.deadline))>120,'121-150',
IF((DATEDIFF('2017-1-1',u.deadline))>90,'91-120',IF((DATEDIFF('2017-1-1',u.deadline))>60,'61-90',
IF((DATEDIFF('2017-1-1',u.deadline))>30,'31-60',IF((DATEDIFF('2017-1-1',u.deadline))>0,'1-30','0未到期')))))))) loan_age,
u.principle AS amount
FROM `repayment_plan_2016_201612` u
JOIN pay_detail pay ON u.product_no = pay.product_no AND pay.trans_time <'2017-01-01'
WHERE
u.repay_no IS NULL
GROUP BY 1,deadline)t0
WHERE t0.amount>0
GROUP BY t0.product_no;