Question

I have three tables.

Properties

property_id

Reservations:

reservation_id
reservation_property_id
reservation_date

Payments

payment_id
payment_reservation_id
payment_amount

A reservation can have many payments associated with it and a property can have many reservations.

What I am trying to work out how to do is find out the reservation date that each property reached £500 in revenue.

I therefore need to work out the cumulative sum of the payment amounts and find out the date that the threshold of £500 was reached for each property.

Hopefully this makes sense.

Thanks in advance for your help.

Was it helpful?

Solution

Please have a try with this one:

SELECT reservation_property_id, MIN(reservation_date) 
FROM (SELECT IF(@prevProperty != q.reservation_property_id, 
                @runningtotal:=0, 
                @runningtotal:=@runningtotal + payment_amount) AS runningtotal,
             @prevProperty := q.reservation_property_id, q.*
      FROM (SELECT *
            FROM reservations r 
            INNER JOIN payments p 
                    ON p.payment_reservation_id = r.reservation_id 
                    /*not sure how your tables are linked*/
            , (SELECT @runningtotal:=0, @prevProperty:=0) vars
            ORDER BY r.reservation_property_id, reservation_date) q
      ) sq
WHERE runningtotal >= 500
GROUP BY reservation_property_id

I didn't join to Properties table, though, out of convenience :)

The idea is basically just to calculate the running total of payments on the table ordered by property and date. In the outer query just select the minimum date where the running total is equal or greater the threshold.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top