2017-11-03 9 views
4

私はそうのようなクエリがあります。PHPではなくMYSQLクエリでこの算術演算を直接行うことはできますか?

$total_revenue = 0; 
$total_spending = 0; 

foreach($rows as $row) { 
    $total_revenue += $row['revenue']; 
    $total_spending += $row['spending']; 
} 

$total_profit = ($total_revenue - $total_spending); 

echo $total_profit; 

だから、基本的に私は、減算することにより、キャンペーンの総利益を取得しようとしている:

$query = "SELECT * FROM `profit_by_campaign` WHERE campaign_name = 'myCoolCampaign' AND request_date = '2017-10-16'"; 

try { 
    $stmt = $this->dbh->prepare($query); 
    $stmt->execute(); 
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); 
} 
catch(PDOException $e) { 
    die('Error: unable to query ' . $e->getMessage()); 
} 

結果を取得した後、私はそうのようないくつかのロジックを実行しますがそれは収入からの支出です。私の質問は、PHPではなくMySQLのクエリ自体でこのロジックを直接行うことが可能なのでしょうか?

+0

はい、のような[集計関数(https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html)を使用して[ SUM()](https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_sum) –

+4

はい、可能です。 –

+0

合計(収益+支出)as total_profit –

答えて

7

は、このクエリを実行してください。

SELECT SUM(revenue - spending) AS profit 
FROM profit_by_campaign 
WHERE 
    campaign_name = 'myCoolCampaign' AND 
    request_date = '2017-10-16'; 
+1

@JayBlanchard '$ total_profit =($ total_revenue - $ total_spending); ' –

+0

すべてを集計していますが、最後は差分を取っています。 –

+0

おっと、悪いです。コーヒーが足りません。 +1 –

関連する問題