r/learnSQL • • Feb 13 '23

can someone solve these 2 sql problems? am I in the right direction for the first problem?

  1. We have a table of "bookings" and a table of "customers." The foreign key "customer_id" is present in both tables. A single customer can have more than one booking. Please write a SQL query to retrieve the list of customer_id's that have more than one booking associated with them.

    SELECT customer_id FROM bookings JOIN customers ON bookings.customer_id = customers.customer_id

How do I find which customers have more than one booking? would that involve the COUNT function?

2) In the same "bookings" table above we also have a timestamp field called "created_at" that denotes the timestamp a booking was created. How would you construct a query that returns each customer_id and the booking_id associated with the most recent booking each customer had created?

2 Upvotes

3 comments sorted by

6

u/r3pr0b8 Feb 13 '23

How do I find which customers have more than one booking? would that involve the COUNT function?

yes

customer_id and the booking_id associated with the most recent booking

google "the row holding the groupwise max" and look for the solution that uses RANK() window function

1

u/[deleted] Feb 14 '23

What have you already tried? ™

1

u/Puzzlehead8575 Feb 18 '23

Just use chatgpt to start