I have a table transactions:
client_id Amount payment ref contract type
1 300 MTV 1
1 300 MTV 1
1 300 MTV 1
1 150 ML 1
2 150 ML 2
2 150 ML 2
2 150 ML 2
2 150 ML 2
If a client is on contract 1, then their total payments should be 3 x MTV(300) and 3 x ML(150). If they are on contract 2, then they pay 6 x ML(150).
I am trying to figure out how to get the total number of payments remaining for each client based on their contract type. For example client_id = 1:
client_id type Total Paid Payments remaining
1 MTV 900 0
1 ML 150 2
I can do the first three columns using this:
SELECT `client_id`,
`payment ref` AS `type`,
SUM(`Amount`) as `Total Paid`
FROM transactions
WHERE client_id = 1
GROUP BY type;
How do I add on the payments remaining column?
CASE WHEN `contract type` = 1 THEN (3 - COUNT(MTV)... ?