MYSQL SUM的正负值

时间:2017-02-08 23:54:02

标签: php mysql

我有一个专栏名称' AmountLC'在db表中。另一个专栏名称' DebitCredit'确定' AmountLC'是积极的还是消极的。如果DebitCredit =" H",AmountLC中的值为负数。如果DebitCredit =" S",AmountLC中的值为Positive。我需要进行查询以获得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'];

更新结果代码: SELECT AmountLCDebitCredit FROM T1_CSV_Table WHERE TaxCode =" A0" AND月=" 12"

enter image description here

2 个答案:

答案 0 :(得分:1)

如果您想要的只是借方和贷方的总额

,您可以一次性完成该计算
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

答案 1 :(得分:-1)

请试试这个:

SELECT
    SUM(IF(DebitCredit='H', DebitCredit, 0) AS NegativeTotal,
    SUM(IF(DebitCredit='S', DebitCredit, 0) AS PostiveTotal
FROM T1_CSV_Table 
WHERE
    MONTH='$getMonth'
AND
    TaxCode='A0';