Have a look at the methods Mage_Core_Model_Resource_Db_Collection_Abstract::addExpressionFieldToSelect()
for standard models:
/**
* Add attribute expression (SUM, COUNT, etc)
* Example: ('sub_total', 'SUM({{attribute}})', 'revenue')
* Example: ('sub_total', 'SUM({{revenue}})', 'revenue')
* For some functions like SUM use groupByAttribute.
*
* @param string $alias
* @param string $expression
* @param array $fields
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
public function addExpressionFieldToSelect($alias, $expression, $fields)
And Mage_Eav_Model_Entity_Collection_Abstract::addExpressionAttributeToSelect()
for EAV models:
/**
* Add attribute expression (SUM, COUNT, etc)
*
* Example: ('sub_total', 'SUM({{attribute}})', 'revenue')
* Example: ('sub_total', 'SUM({{revenue}})', 'revenue')
*
* For some functions like SUM use groupByAttribute.
*
* @param string $alias
* @param string $expression
* @param string $attribute
* @return Mage_Eav_Model_Entity_Collection_Abstract
*/
public function addExpressionAttributeToSelect($alias, $expression, $attribute)
Usage
$collection->addExpressionFieldToSelect("page_view", "sum({{page_view}})", ["page_view"]);
// ^ alias ^ expression ^ used fields
$collection->getSelect()->group("page_view""main_table.entity_id");
or
$collection->addExpressionAttributeToSelect("page_view", "sum({{page_view}})", "page_view");
// ^ alias ^ expression ^ used attribute
$collection->groupByAttribute>getSelect("page_view")->group("main_table.entity_id");
Note that the method suggested in the doc block, groupByAttribute()
is only used to group by EAV attributes, not static columns like the entity id.