select * from (select borrowId,month(repayDate) months , hasPI from t_repayment) as ord pivot(sum(hasPI) for months in([12],[1],[2],[3]))as p