sql server - Sql querying same table for overlapping dates -
i'm trying write query overlap in date range reported.
i able several queries, , loops, wondered if made more efficient 1 query, table joins itself.
the table structure is:
create table [dbo].[rentals]( [id] [int] identity(1,1) not null, [room_id] [int] not null, [check_in] [datetime] not null, [check_out] [datetime] not null, [customer_ref] [bigint] null)
so given same room_id, want able query if other booking same room_id falls between check_in , check_out of booking same room_id (to avoid double bookings).
i have use normal code, rather linq due existing project.
this have far, appears returning records:
select r1.id, r1.room_id, r1.check_in, r1.check_out,r1.customer_ref tblrental r1 inner join tblrental r2 on r1.room_id = r2.room_id , r1.check_in < r2.check_out , r1.check_out > r2.check_in
can refine query return records room_id same, , there overlap?
thanks help,
mark
i think problem crossing each row itself, , that's why query returns rows. make sure r1.id <> r2.id
:
select r1.id, r1.room_id, r1.check_in, r1.check_out,r1.customer_ref tblrental r1 inner join tblrental r2 on r1.room_id = r2.room_id , r1.check_in < r2.check_out , r1.check_out > r2.check_in , r1.id <> r2.id
Comments
Post a Comment