3

I have created a custom collection factory. Now I want the sum of a column,how can I achieve it. Here is my code

$collection = $this->customFactory->create()->addFieldToFilter('status',2)  ->addFieldToFilter('customer_id',2)
->columns('SUM(total) AS total')
->group('customer_id');
7
$collection = $this->customFactory->create()->addFieldToFilter('status',2)  ->addFieldToFilter('customer_id',2);

$collection->getSelect()->columns(['total' => new \Zend_Db_Expr('SUM(total)')])->group('customer_id');;
5

If it is a simple expression (as in this way) almost the same way as you add fields to select .... It is called expression field

$collection = $this->customFactory->create() ->addFieldToFilter('status',2) ->addFieldToFilter('customer_id',2) ->addExpressionFieldToSelect('this_is_total', 'SUM({{total}})', 'total');

and the group

$collection ->getSelect() ->group('customer_id');

if your expression is complex, use Rakesh's solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.