我有一张桌子上的数据库' account'它有各种类型的交易。我成功地执行了查询以找到" Total Credit"和"总借记"。我需要帮助来计算余额。即,如果"总积分>总借记额"答案应该是" Balance Cr。"否则如果"总积分<总借记额"答案应该是"平衡博士"否则答案应该是" 0"
<?php
$pp= ("SELECT SUM(amount) FROM account WHERE (mode='cash' AND type='payment') OR (mode='cash' AND type='purchase')");
$total_pp = mysql_query($pp);
while($gtotal_pp = mysql_fetch_array($total_pp)){
echo "<table><tr><td>Total Credit</td><td>:</td><td>$</td><td align='right'>" . $gtotal_pp['SUM(amount)'] . "</td></tr>";
echo "<br/>";
}
$sr = ("SELECT SUM(amount) FROM account WHERE (mode='cash' AND type='sale') OR (mode='cash' AND type='reciept')");
$total_sr = mysql_query($sr);
while($gtotal_sr = mysql_fetch_array($total_sr)){
echo "<tr><td>Total Debit</td><td>:</td><td>$</td><td align='right'>" . $gtotal_sr['SUM(amount)'] . "</td></tr>";
}
$bgtotal_pp = $gtotal_pp['SUM(amount)'];
$bgtotal_sr = $gtotal_sr['SUM(amount)'];
$balance_cr = $bgtotal_pp - $bgtotal_sr;
$balance_dr = $bgtotal_sr - $bgtotal_pp;
if ($bgtotal_pp > $bgtotal_sr)
echo "<tr><td>Balance (Cr.)</td><td>:</td><td>$</td><td align='right'>" . $balance_cr . "</td></tr></table>";
else if ($bgtotal_pp < $bgtotal_sr)
echo "<tr><td>Balance (Dr.)</td><td>:</td><td>$</td><td align='right'>" . $balance_dr . "</td></tr></table>";
else
echo"<tr><td>Balance</td><td>:</td><td></td><td align='right'>0.00</td></tr></table">;
?>
何时
$bgtotal_pp = "(some number)";
$bgtotal_sr = "(some number");
代码完美无缺。只有当我尝试使用上一个查询而不是某个数字时,它才会显示&#34; Else语句&#34;。
提前致谢。
答案 0 :(得分:1)
这是关于查询,而不是php代码(有使用mysql_等问题)。为什么要在应用程序中进行多个查询然后进行算术运算。您可以使用一个查询完成所有这些操作:
SELECT SUM(CASE WHEN mode = 'cash' and type in ('payment', 'purchase') then amount end) as Credit,
SUM(CASE WHEN mode = 'cash' and type in ('sale', 'receipt') then amount end) as Debit,
SUM(CASE WHEN mode = 'cash' and type in ('payment', 'purchase') then amount
WHEN mode = 'cash' and type in ('sale', 'receipt') then - amount
ELSE 0
END) as Balance
FROM account;
通常情况下,我希望where
条款或group by
获取特定帐户的信息,但这不在原始数据中。