SELECT `b`.*, `actGrp`.`acctTypeID`, (select SUM(pnl.amountdr) from view_comp_acc_det pnl where pnl.acctID = b.ID and pnl.year =2015 and pnl.period <=9 ) as PNLdr, (select SUM(pnl.amountcr) from view_comp_acc_det pnl where pnl.acctID = b.ID and pnl.year =2015 and pnl.period <=9 ) as PNLcr, `a`.`amountdr` as thismonthdr, `a`.`amountcr` as thismonthcr, IFNULL((select debit from comp_opening_balance where companyID = b.companyID and accountID = b.ID and year =2015), 0) as oDebitPNL, IFNULL((select credit from comp_opening_balance where companyID = b.companyID and accountID = b.ID and year =2015), 0) as oCreditPNL, IFNULL((select debit from comp_opening_balance where companyID = b.companyID and accountID = b.ID and year =2015), 0) as oDebit, IFNULL((select credit from comp_opening_balance where companyID = b.companyID and accountID = b.ID and year =2015), 0) as oCredit, ifnull(SUM(c.amountdr), 0) as yeardebit, ifnull(SUM(c.amountcr), 0) as yearcredit
FROM (`comp_chart_of_acct` b)
LEFT OUTER JOIN `view_comp_acc_det` a ON `a`.`acctID` = `b`.`ID` and a.year =2015 and a.period =9
LEFT JOIN `_ref_acct_group` actGrp ON `actGrp`.`ID` = `b`.`acctGroupID`
LEFT OUTER JOIN `view_comp_acc_det` c ON `b`.`ID` = `c`.`acctID` and CONCAT(c.year,if(c.period<=9, CONCAT("0",c.period),c.period)) <= 201509 and c.year >= 2015
WHERE `b`.`companyID` =  '3'
GROUP BY `b`.`acctCode`
ORDER BY `b`.`acctCode`