I have accounts which have category associated with it & orders table where order can be either debt or credit based on “order_type” field & a payment table which stores the date of payment along with the amount (no negative numbers used for debt or credits).
currently I am using something like this:
SELECT cat, SUM(p.amount) balance
FROM accounts a
LEFT JOIN orders o ON a.id = o.account_id
LEFT JOIN payments p ON o.id = p.order_id
WHERE YEAR(p.date) = 2012
GROUP BY a.cat
The first issue:
This would count all as paid-in money which is wrong, I’ve tried to use
sum(IF(o.order_type = 1, p.amount, p.amount * -1 ))
which failed to give me correct result as all amounts were negative.
Second issue:
It won’t show categories where no payments were made, the limiting factor here is the date which I need to make sure that I am counting payments on 2012 only but I also want to show all categories with zeros if no payments were made.
Am I approaching it the WRONG way?
If anyone knows a solution for either issues or both, please provide your solution on this.
The year check has to be in the JOIN condition, not WHERE, so it won’t exclude the categories with no payments.