In PHP MySQL
SELECT `main_table`.`rebate_amount`, `main_table`.`companyname`, (SELECT target FROM batecash WHERE id = MAX(main_table.id)) AS `maxtarget`, SUM(rebate_amount) AS `rebate_amount`, SUM(invoiceamount) AS `purchase_amount`, MAX(id) AS `max_id`, `main_table`.`rebatetarget`, YEAR(created_at) yr, QUARTER(created_at) qt FROM `batecash` AS `main_table` WHERE (customerid = '5') GROUP BY YEAR(created_at), QUARTER(created_at) ORDER BY `created_at` DESC
In Magento
$rebatecount = Mage::getModel('rebatereward/batecash')->getCollection()
->addFieldToSelect('rebate_amount')
->addFieldToSelect('companyname')
->addFieldToFilter('orderstatus', array('eq' => 'completed'))
->addFieldToFilter('addressid', array('eq' => $address->getId()))
->addFieldToFilter('customerid', array('eq' => $this->getCustomer()->getId()));
$rebatecount->getSelect()->columns("(SELECT rebatetarget FROM batecash WHERE id = MAX(main_table.id)) as maxtarget");
$rebatecount->getSelect()
->columns('SUM(rebate_amount) as rebate_amount')
->columns('SUM(invoiceamount) as purchase_amount')
->columns('MAX(id) as max_id')
->columns('rebatetarget')
->columns('YEAR(created_at) yr, QUARTER(created_at) qt')
->group('YEAR(created_at), QUARTER(created_at)')
->order(array('created_at DESC'));