如果存在多个日期间隔,如何找到最合适的给定日期

时间:2014-09-12 09:19:19

标签: sql

我有两张桌子,其中有结账日期和其他有关客户和其他表的信息,房价类型的酒店ID和日期从何时到有效率。现在的问题是,如果费率表有三个开始和结束日期,并且检入日期位于其中三个日期范围中它显示三个记录,而要求是它应该选择最近的开始日期例如是

start date  end date   room rate  
2013-10-01  2014-03-31 2000
2013-11-01  2013-12-20 2500
2013-12-21  2013-12-31 3000

并且入住日期是25-12-2013它应该显示记录,只有最适合它的日期范围3 我的SQL查询如下           `

 select b.*, r.* from(select a.Enquiry_Id,a.Ckeck_In,a.check_Out,a.Place,a.Hotel_Name,a.Meal_Plan,a.Room_Type,a.Occupancy_Type,a.Extra_Bed,a.Room_QT,h.grade,
 h.addres, h.Hotel_ID, a.ChildWithBed,a.childAgeWithoutBed,
 a.Inclusion, a.No_Night from Accomodation a inner join hotel h on
 a.Hotel_Name = h.Hotel_Name where a.Enquiry_Id = '0128201408') b inner
 join  RoomType r on b.Hotel_ID = r.Hotel_ID where r.Name = b.Room_Type
 and b.Ckeck_In between r.StartSeason and r.EndSeason order by Ckeck_`In

1 个答案:

答案 0 :(得分:0)

尝试这样的smth:

with (
    select 
        a.Enquiry_Id,a.Ckeck_In,a.check_Out,a.Place,
        a.Hotel_Name,a.Meal_Plan,a.Room_Type,
        a.Occupancy_Type,a.Extra_Bed,a.Room_QT,h.grade,
        h.addres, h.Hotel_ID, a.ChildWithBed,a.childAgeWithoutBed,
        a.Inclusion, a.No_Night 
    from Accomodation a 
    join hotel h on
        a.Hotel_Name = h.Hotel_Name 
    where 
        a.Enquiry_Id = '0128201408'
) temp
select
    temp.*, r.*
from temp
join (
    select 
        r.Hotel_ID, temp.Enquiry_Id, min(datediff(day, r.StartSeason, temp.Check_In)) MinDateDiff
    from temp
    join RoomType r on 
        temp.Hotel_ID = r.Hotel_ID 
    where 
        r.Name = temp.Room_Type
        and temp.Ckeck_In between r.StartSeason and r.EndSeason
    group by
        r.Hotel_ID, temp.Enquiry_Id
) x on
    temp.Enquiry_Id = x.Enquiry_Id
    and temp.Hotel_ID = x.Hotel_ID
join RoomType r on 
    x.Hotel_ID = r.Hotel_ID 
where 
    r.Name = temp.Room_Type
    and temp.Ckeck_In between r.StartSeason and r.EndSeason
    and datediff(day, r.StartSeason, temp.Check_In) = x.MinDateDiff
order by
    temp.Check_In

我正在计算StartSeason和Check_In之间的min datediff,将它放在子查询中,然后依靠这个datediff来获取最近的记录。 我可以在子查询分组和最外面的连接中犯错误。只需检查并在需要时更正。