这个问题与我之前的帖子有关:MySQL - 查询中的复杂 SUM
该查询运行良好,可以根据需要汇总总数。我注意到它也忽略了任何具有 NULL 值的记录。
当前查询:
SELECT c.*,
SUM(CASE WHEN billtype = 1 THEN total ELSE 0 END) totalpaid ,
SUM(CASE WHEN billtype = 2 THEN total ELSE 0 END) totalowed ,
SUM(total) AS totalbalance
FROM
tbl_customers c
LEFT JOIN tbl_customers_bills b
ON c.customerid = = b.customerid
and billtype in (1,2)
GROUP BY
c.customerid
它还漂亮地返回了10条客户记录。当我检查数据库时,我可以看到11tbl_customers_bills
条客户记录,而第 11 条在表中没有相关记录。
即使tbl_customers_bills
表中不存在记录,我仍想返回所有 11 个。(但当然是零)
我不知道这种情况会变得多么复杂。这是我尝试过的:(无济于事)
SELECT c.*,
(CASE WHEN (total IS NULL) THEN totalpaid = 0
ELSE
SUM(CASE WHEN billtype = 1 THEN total ELSE 0 END) totalpaid ,
SUM(CASE WHEN billtype = 2 THEN total ELSE 0 END) totalowed ,
SUM(total) AS totalbalance
END)
FROM
tbl_customers c
LEFT JOIN tbl_customers_bills b
ON c.customerid = = b.customerid
and billtype in (1,2)
GROUP BY
c.customerid