This question is related to my previous post: MySQL - Complicated SUMs inside Query
The query is working great, summing up the totals as desired. I notice that it also ignores any records with NULL values.
Current query:
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
And it returns 10 customer records beautifully.
As I check the database, I can see 11 customer records, and the eleventh has no correlating records inside the tbl_customers_bills
table.
I'd like to still return all eleven, even if there are non-existing records in the tbl_customers_bills
table. (but with zeros, of course)
I'm stuck with how complicated such a condition can get. Here's what I've tried: (to no avail)
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