I have a customer credit table and a booking table, shown below. I’ve executed the following query which works but it’s too simple. I now need to cross join my original query to the booking table so I can check for where the booking status is completed. My second query is wrong because it SUMs the adjustment for each booking.
Initial working query
x
select customer_id, SUM(adjustment) from customer_credit group by customer_id;
Query with join
select c.customer_id, SUM(c.adjustment)
from customer_credit c
inner join booking b
on b.customer_id = c.customer_id
group by c.customer_id;
Customer credit
| id | customer_id | adjustment |
| 1 | 1234567 | 50 |
Booking
| id | status | customer_id |
| 1 | completed | 1234567 |
Advertisement
Answer
Do the sum first and then join
:
select c.customer_id, c.adjustments, b.*
from (select c.customer_id, sum(c.adjustment) as adjustments
from customer_credit c
group by c.customer_id
) c left join
booking b
on b.customer_urn = c.customer_id;
Note: I suspect that you might want a left join
to handle customers with no adjustments.