Skip to content
Advertisement

Simple query to join with my booking table without duplicating records for each booking

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

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement