PHP MYSQL查询如何只有SUM正值

时间:2017-09-28 03:07:17

标签: php mysql

我想知道如何只为SUMalldebt补偿正值。这是我的一些代码。从代码中,我获得了正负值的金额。如何获得所有正数金额?谢谢

if($idrange=='0'):
     $where     = "AND c.debt > 0 OR c.debt < 0";
  elseif($idrange=='1'):
      $where    = "AND c.debt < 0";
  elseif($idrange=='2'):
      $where    = "AND c.debt >= 0 AND c.debt < 3000";
  elseif($idrange=='3'):
      $where    = "AND c.debt >= 3000 AND c.debt < 5000";  endif;

这是我的查询

$querydebtor         = "SELECT * FROM
            (SELECT debtor,debt,
    SUM(case WHEN (debt < 0 ) then 1 else 0 end) AS debnegk,
    SUM(case WHEN (debt >= 0 AND debt < 3000) then 1 else 0 end) AS deb3k,
    SUM(case WHEN (debt >= 3000 AND debt < 5000) then 1 else 0 end) AS deb5k,
    SUM(debt) as amountalldebt
    FROM debt WHERE debt > 0 AND $where)";
    $ldebtor = $this->db->query($querydebtor)->result(); 

    foreach ($ldebtor as $x) {
    $amountalldebt   = $a->amountalldebt;}

    <td><?php echo $amountalldebt;?></td>

1 个答案:

答案 0 :(得分:-1)

在sql语句中过滤它以仅显示正值

$querydebtor         = "SELECT amountalldebt FROM
            (SELECT debtor,debt,
    SUM(case WHEN (debt < 0 ) then 1 else 0 end) AS debnegk,
    SUM(case WHEN (debt >= 0 AND debt < 3000) then 1 else 0 end) AS deb3k,
    SUM(case WHEN (debt >= 3000 AND debt < 5000) then 1 else 0 end) AS deb5k,
    SUM(debt) as amountalldebt
    FROM debt WHERE debt > 0 AND $where)";

$ldebtor = $this->db->query($querydebtor)->result(); 

    foreach ($ldebtor as $x) {
    $amountalldebt   = $amountalldebt + $x;}