Mysql Substract基于大于条件的两列

时间:2017-11-21 06:07:40

标签: mysql

我正在从TotalAmt减去NetTotal,但是当TotalAmt小于NetTotal时,则Due显示负值。如果TotalAmt小于NetTotal,我如何显示为零。我查询检索到期金额是

SELECT DISTINCT id,
                name,
                TotalAmt,
                NetTotal,
                Due
FROM
  (SELECT u.id,
          u.name,

     (SELECT SUM(amt)
      FROM pay_master
      WHERE refsid = u.id
        AND typ IN ('std_deposit',
                    'sale_ind')
      GROUP BY refsid) AS 'TotalAmt',

     (SELECT IFNULL(SUM(net_total), 0)
      FROM trans_master t
      WHERE t.refid = u.id
      GROUP BY t.refid) AS 'NetTotal',
          IFNULL(
                   (SELECT IFNULL(SUM(amt), 0)
                    FROM pay_master p
                    WHERE p.refsid = u.id
                      AND typ IN ('std_deposit', 'sale_ind')
                    GROUP BY refsid) -
                   ( SELECT IFNULL(SUM(net_total), 0)
                    FROM trans_master t
                    WHERE t.refid = u.id
                    GROUP BY t.refid), 0) AS 'Due'
   FROM USER u
   INNER
    JOIN pay_master p ON p.refsid = u.id
   AND u.typ = 'std')x

1 个答案:

答案 0 :(得分:0)

你在找这个吗?

SELECT DISTINCT id,
  name,
  TotalAmt,
  NetTotal,
  case when Due < 0 then 0 else Due end
FROM
  (SELECT u.id,
    u.name,
    (SELECT SUM( amt )
    FROM pay_master
    WHERE refsid = u.id
    AND typ     IN ( 'std_deposit', 'sale_ind')
    GROUP BY refsid
    ) AS 'TotalAmt',
    (SELECT IFNULL( SUM( net_total ) , 0 )
    FROM trans_master t
    WHERE t.refid = u.id
    GROUP BY t.refid
    ) AS 'NetTotal',
    IFNULL(
    (SELECT IFNULL( SUM( amt ) , 0 )
    FROM pay_master p
    WHERE p.refsid = u.id
    AND typ       IN ( 'std_deposit', 'sale_ind')
    GROUP BY refsid
    ) -
    (SELECT IFNULL( SUM( net_total ) , 0 )
    FROM trans_master t
    WHERE t.refid = u.id
    GROUP BY t.refid
    ) , 0) AS 'Due'
  FROM USER u
  INNER JOIN pay_master p
  ON p.refsid = u.id
  AND u.typ   = 'std'
  )x

使用案例来维持这种情况