I am using following sql query…
SELECT COALESCE(s.open_bal,0)
AS open_balance
, COALESCE(sum(i.amount),0)
AS gross_fee
, COALESCE(sum(i.discount),0)
AS discount
, COALESCE(sum(i.amount) - sum(i.discount),0)
AS net_payable
, COALESCE(SUM(r.reg_fee+r.tut_fee+r.other_fee),0)
AS net_recieved
, COALESCE(sum(i.amount), 0)
- COALESCE(sum(i.discount), 0)
- COALESCE(SUM(r.reg_fee+r.tut_fee+r.other_fee), 0)
AS balance_due
, b.name
AS batch
, b.id
AS batch_id
FROM batches
Then just add
IF()for a negative balance:edit: Moving on to fix the query.
going down from subscribers to both invoices and receipts is wrong idea itself. You’re joining receipts to invoices, and if there are more then 1 of any, the other side of join will be summed twice (N times, actually).
Now, I’ll give a basic idea how the query should look. I’m not going into COALESCE() thing – I believe it’s unnecessary, as
SUM()shouldn’t returnNULLs.You get the idea.