我有三张桌子。
属性
property_id
预订
reservation_id
reservation_property_id
reservation_date
付款
payment_id
payment_reservation_id
payment_amount
预订可能会有很多与之相关的付款,而且酒店可能有很多预订。
我想弄清楚如何做的是找出每个物业的收入达到500英镑的预订日期。
因此,我需要计算出支付金额的累计金额,并找出每个房产达到500英镑门槛的日期。
希望这是有道理的。
提前感谢您的帮助。
答案 0 :(得分:0)
请试试这个:
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
但是,出于方便,我没有加入Properties表:)
这个想法基本上只是计算按属性和日期排序的表格上的付款总额。在外部查询中,只需选择运行总计等于或大于阈值的最小日期。