如何从数据库中获取两个字段的总和

时间:2013-01-07 14:26:27

标签: php mysql

$query = "SELECT agent_id, SUM(amount) FROM bill WHERE YEAR(date)  = YEAR(CURDATE()) AND MONTH(date) = MONTH(CURDATE()) GROUP BY agent_id"; 

$result = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result)){
    echo "Total ". $row['agent_id']. " = $". $row['SUM(amount)'];
    echo "<br />";
}

DB结构图像:

Database structure

我想知道怎样才能显示支票金额和当前金额仅为金额的总和

3 个答案:

答案 0 :(得分:0)

试试这个(我从你的问题中理解的) -

SELECT agent_id, (SUM(amount)+sum(cheque)) As total FROM bill WHERE YEAR(date)  = YEAR(CURDATE()) AND MONTH(date) = MONTH(CURDATE()) GROUP BY agent_id"; 

答案 1 :(得分:0)

当然可以,您的查询将如下所示:

SELECT agent_id, SUM(amount + cheque) 
FROM bill 
WHERE YEAR(date) = YEAR(CURDATE()) 
AND MONTH(date) = MONTH(CURDATE()) 
GROUP BY agent_id

答案 2 :(得分:0)

SELECT agent_id, (SUM(amount) + SUM(cheque)) AS total_amount
FROM bill WHERE YEAR(date)  = YEAR(CURDATE()) AND MONTH(date) = MONTH(CURDATE()) 
GROUP BY agent_id