MySQL 带条件的字段的 SUM,IF(SUM(bill_1) IS NULL, '99', SUM(bill_1)) AS tot_bill_1

MySQL SUM of field with conditon, IF(SUM(bill_1) IS NULL, '99', SUM(bill_1)) AS tot_bill_1

我想要 SUM(tot_bill_1+tot_bill_2) AS total,但它不起作用

SELECT *, 
IF(SUM(bill_1) IS NULL, '99', SUM(bill_1)) AS tot_bill_1, 
IF(SUM(bill_2) IS NULL, '10', SUM(bill_2)) AS tot_bill_2, 
SUM(tot_bill_1+tot_bill_2) AS total
FROM billing

有什么想法吗?

您可以使用子查询来做到这一点:

SELECT sum_bill1,
       sum_bill2,
       (sum_bill1 + sum_bill2) AS total
FROM
  (SELECT COALESCE(sum(bill1), 99) AS sum_bill1,
          COALESCE(sum(bill2), 10) AS sum_bill2
   FROM billings) t