Jump to content

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...

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.