I want to calculate sum of all total_purchase values whose ref_by value is 1. Table name is table_name. Can someone please help me.

I want sql query which will return total (200 + 97 + 140)

enter image description here

  • Did you resolve your query? Commented Mar 24, 2019 at 5:17

2 Answers 2


Query is simple, try this:

SELECT SUM(total_purchase) AS 'sum_total_purchase' FROM  table_name
WHERE ref_by=1

Try it, it will surely work.


You can use direct SQL method to get the desired result:-

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('memory_limit', '5G');

use Magento\Framework\App\Bootstrap;
require '../app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('table_name'); //gives table name with prefix

//Select Data from table
$sql   = "SELECT SUM(total_purchase) AS 'sum_total_purchase' FROM ".$tableName."" WHERE ref_by = 1";
$result = $connection->fetchAll($sql);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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