我想获取医院账单的收款报告。有一张表记录了患者支付的预付款金额。并非所有患者都预付费用。
这是我现在使用的查询
"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
表中的值不会添加到总和中。
最佳答案
如果将 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)
关于php - 使用 CASE WHEN 时,如果 LEFT JOIN 中找不到匹配行,则忽略列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39697414/