mcanedo
mcanedo

Reputation: 445

How to calculate the due amount of this payments?

I want to create a query to calculate the due amount, on a situation where partial payments can be done for specific paymentSchedule id

I have a table with a payment schedule as this:

CREATE TABLE IF NOT EXISTS paymentSchedule (
  id int(11) NOT NULL AUTO_INCREMENT,
  concept varchar(32) COLLATE utf8_spanish_ci NOT NULL,
  student_id int(11) NOT NULL,
  dueDate date NOT NULL,
  amount decimal(10,2) NOT NULL,
  PRIMARY KEY (id)
)

And I have a payments transaction table like this, wherepaymentSchedule_id refers to the above table:

CREATE TABLE IF NOT EXISTS ledger (
  id int(11) NOT NULL AUTO_INCREMENT,
  paymentDate date NOT NULL,
  amount decimal(10,2) NOT NULL,
  paymentSchedule_id int(11) NOT NULL,
  PRIMARY KEY (id)
  )

I tried to to a substraction like here: How to substract from the resut of two selects in mysql

but that only works if there are fields with the correspondinf paymentSchedule id in the ledger. What is the right way to do it?

on the other hand, is that the right way to store payment schedules and transactions?

Upvotes: 0

Views: 311

Answers (1)

mathematical.coffee
mathematical.coffee

Reputation: 56915

It seems like you are trying to do this?

for each id in paymentSchedule table:
    store paymentSchedule.amount - sum( ledger.amount )

In which case you could do:

SELECT paymentSchedule.id, 
       paymentSchedule.amount - IFNULL(SUM(ledger.amount),0) AS remaining
FROM paymentSchedule
LEFT JOIN ledger ON paymentSchedule.id=ledger.paymentSchedule_id
GROUP BY ledger.paymentSchedule_id

This shows all amounts remaining, regardless of whether a person has paid any of it off or not (thanks to the IFNULL( xxx, 0 )).

Upvotes: 1

Related Questions