我想获取为医院支付的账单的收集报告。有一张桌子记录了患者支付的预付金额。并非所有患者都预付款。
这是我现在使用的查询
"SELECT SUM(
CASE
WHEN bill_type = 3 THEN b.payable_amount + w.balance
ELSE 0
END) AS 'amount'
FROM bills b
LEFT JOIN ip_patients ip on ip.id = b.ip_id
LEFT JOIN advance w on w.id = (SELECT x.id FROM advance x WHERE x.ip_id = ip.id ORDER BY x.created_at DESC LIMIT 1)
WHERE b.doctor_id = '$d->id' AND CAST(b.created_at AS DATE) >= '$date1' AND CAST(b.created_at AS DATE) <= '$date2' AND b.is_cancelled = 0 AND b.is_deleted = 0"
如果患者未支付预付款,则advance
表中不会插入任何行。上述查询会发生的情况是,当患者在预先表中没有行时,他的付款被完全忽略(即,bills
表中的值未添加到总和中。
答案 0 :(得分:2)
如果将null添加到非null,则结果为null。例如
MariaDB [sandbox]> set @a = null;
Query OK, 0 rows affected (0.00 sec)
MariaDB [sandbox]> set @b = 100;
Query OK, 0 rows affected (0.00 sec)
MariaDB [sandbox]>
MariaDB [sandbox]> select @a+@b amt;
+------+
| amt |
+------+
| NULL |
+------+
1 row in set (0.00 sec)
你可以用ifnull来处理这个
set @a = null;
set @b = 100;
select ifnull(@a,0) + ifnull(@b,0) amt;
+-----+
| amt |
+-----+
| 100 |
+-----+
1 row in set (0.00 sec)