Saturday 22 July 2017

How to get the latest record in each group using GROUP BY


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'));

Wednesday 19 July 2017

Which table truncate for magento speed optimised

SET foreign_key_checks = 0;
TRUNCATE dataflow_batch_export;
TRUNCATE dataflow_batch_import;
TRUNCATE log_customer;
TRUNCATE log_quote;
TRUNCATE log_summary;
TRUNCATE log_summary_type;
TRUNCATE log_url;
TRUNCATE log_url_info;
TRUNCATE log_visitor;
TRUNCATE log_visitor_info;
TRUNCATE log_visitor_online;
TRUNCATE report_viewed_product_index;
TRUNCATE report_compared_product_index;
TRUNCATE report_event;
TRUNCATE index_event;
TRUNCATE catalog_compare_item;
SET foreign_key_checks = 1;