问题
I have two tables:
booking
- records the order detailid | booking_amount ------------------- 1 | 150 2 | 500 3 | 400
payment
- records the payment for orderid | booking_id | amount ------------------------ 1 | 1 | 100 2 | 1 | 50 2 | 2 | 100
I want to find all bookings where the payments are not complete. With the above data, we expect the answer to be 2,3
, because the sum of payments for booking_id=1
matches the corresponding booking_amount
in the booking_table
.
回答1:
To answer your question, you have 2 things you need to think about :
you want the total amount in your table
payment
by every booking rowyou want to join your
booking_amount
table withpayment
.
Part 1 is quite simple:
SELECT sum(amount) as TotalP, booking_id FROM payment GROUP BY booking_id
Just a basic query with a simple aggregate function...
For part 2, we want to join booking_amount
and payment
; the basic JOIN
would be:
SELECT * FROM booking b
LEFT JOIN payment p ON b.id = p.booking_id
We do a LEFT JOIN
because we may have some booking who are not in the payment
table. For those bookings, you will get NULL
value. We will use a COALESCE
to replace the NULL
values by 0
.
The final query is this:
SELECT b.id, COALESCE(TotalP, 0), b.booking_amount
FROM
booking b
LEFT JOIN
(SELECT sum(amount) as TotalP, booking_id FROM payment GROUP BY booking_id) as T
ON b.id = T.booking_id
WHERE COALESCE(TotalP, 0) < b.booking_amount
回答2:
You need to use a outer join to combine your two tables and look for your conditions. Also, you will need to use SUM(..) function to get the sum of the amount for each id in the payment table.
Please try this:
select b.id from booking b
left outer join -- cant be inner join because we lose id:3 in that case.
(
select booking_id, SUM(amount) as Total
from payment group by booking_id
) p on b.id = p.booking_id
where b.booking_amount > Coalesce(Total,0) --Coalesce is required for such values coming NULL, like id:3, they will be assigned as 0.
来源:https://stackoverflow.com/questions/36452733/sql-query-to-get-data-diffrence-of-total-in-2-tables