我在数据库表中有一个列名“ AmountLC”。另一列名称“ DebitCredit”确定“ AmountLC”是正数还是负数。如果DebitCredit =“ H”,则AmountLC中的值为负。如果DebitCredit =“ S”,则AmountLC中的值为正。我需要进行查询以获取AmountLC的总和。我试图弄清楚逻辑,但是什么也没弄。如果有人可以帮助我,我将不胜感激。

我按照其他stackoverflow讨论尝试了以下代码。

$F7 = mysql_query("SELECT
                SUM(CASE WHEN DebitCredit='H' THEN DebitCredit ELSE 0 END) as NegativeTotal,
                SUM(CASE WHEN DebitCredit='S' THEN DebitCredit ELSE 0 END) as PostiveTotal
                FROM T1_CSV_Table
                WHERE Month='$getMonth' AND TaxCode='A0'");


谢谢!
更新代码

$F7 = mysql_query("SELECT
                    SUM(CASE WHEN DebitCredit='H' THEN AmountLC*-1 ELSE AmountLC END) as Total
                    FROM T1_CSV_Table
                    WHERE Month='$getMonth' AND TaxCode='A0'");
    $rowf7 = mysql_fetch_array($F7);
    echo "Total-".$rowf7['Total'];


更新结果代码:
AmountLCDebitCredit =“ A0”和Month =“ 12”中选择T1_CSV_TableTaxCode

php - 正负值的MYSQL SUM-LMLPHP

最佳答案

如果您想要的只是借方和贷方的总数,则可以一次性完成该计算

SELECT
    SUM(CASE WHEN DebitCredit='H' THEN AmountLC*-1 ELSE AmountLC END) as Total
FROM T1_CSV_Table
WHERE Month='$getMonth' AND TaxCode='A0'



  注意:您的脚本有SQL Injection Attack的风险
  看看Little Bobby Tables发生了什么
  if you are escaping inputs, its not safe!
  使用prepared parameterized statements

08-19 03:46