Jump to content

[SOLVED] Math On Result of Subquery


JonnoTheDev

Recommended Posts

Having difficulty with this query. What I have is a booking system where a user can be assigned to a booking (many bookings). There is a comission rate for each booking that is to be paid to the user. The administrator can see the amount owed per booking and make payments, however they can pay in parts i.e 50 - 2 installments of 25.

 

What I need is the total amount in comission minus the amount paid for all bookings giving the total owed to the user.

 

tables

 

bookings

========

bookingId

userId

price

rate

payMethod

 

user

========

userId

name

 

collection

========

id

bookingId

amount

 

 

Query:

SELECT u.userId, u.name, SUM(b.rate), (SELECT SUM(amount) FROM collection c WHERE b.bookingId=c.bookingId) 

FROM users u INNER JOIN bookings b ON (u.userId=b.userId) 

WHERE b.payMethod='cash' GROUP BY u.userId ORDER BY u.name ASC

 

This gives the correct information but I need to minus the results of (SELECT SUM(amount) FROM collection c WHERE b.bookingId=c.bookingId) from SUM(b.rate).

A simple minus operator gives me a null result.

Link to comment
https://forums.phpfreaks.com/topic/158098-solved-math-on-result-of-subquery/
Share on other sites

SELECT u.userId, u.name, SUM(b.rate) -  SUM(z.amount) AS `Total`

FROM users u INNER JOIN bookings b ON (u.userId=b.userId)
INNER JOIN collection z ON b.bookingId=c.bookingId

WHERE b.payMethod='cash' GROUP BY u.userId ORDER BY u.name ASC

Can't you just do that?

Then `Total` will contain the total amount. Possibly...

 

I have no idea if that'll work.

Try this way

SELECT u.userId, u.name, SUM(b.rate) - (ifnull (SELECT SUM(amount) FROM collection c WHERE b.bookingId=c.bookingId), 0 )

FROM users u INNER JOIN bookings b ON (u.userId=b.userId)

WHERE b.payMethod='cash' GROUP BY u.userId ORDER BY u.name ASC

Not tested...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.