Magento – grid joinTable alias problem in order by

admincollection;customergrid-serlizationsql

I made in customers admin grid a join with sales_flat_order table:

protected function _preparePage()
{     
    $this->getCollection()->joinTable('sales_flat_order', 
                                        'customer_id = entity_id', 
                                        array('ordered' => new Zend_Db_Expr('SUM(subtotal_invoiced)'),), 
                                        null, 
                                        'left');   
    $this->getCollection()->getSelect()->group('entity_id'); 
    return parent::_preparePage();
} 

protected function _prepareColumns()
{     
    $this->addColumnAfter('ordered', array(
        'header'    => Mage::helper('customer')->__('Ordered'),
        'index'     => 'ordered',            
    ),'name');                   
    return parent::_prepareColumns();
}

It works fine, until I try to use sort by field ordered. Magento put into query

ORDER BY sales_flat_order.SUM(subtotal_invoiced) 

and this produces SQL error

FUNCTION sales_flat_order.SUM does not exist.

How can I remove sales_flat_order from ORDER BY so it would be just ORDER BY SUM(subtotal_invoiced)? In select it doesn't put that, it stays SUM(subtotal_invoiced) AS ordered, I don't know why it put in ORDER BY this.

Best Answer

You cannot use Zend_Db_Expr as third param of joinTable, because it should be the array which contains the list of field names from joined table. Try to get select from collection and to use join function for your purpose.

 $this->getCollection()->getSelect()->join(
     array('sfo'=>'sales_flat_order'), 
     'sfo.customer_id = main_table.entity_id', 
     array('ordered' => new Zend_Db_Expr('SUM(sfo.subtotal_invoiced)')) 
 ); 

Hope that will help you.