简体   繁体   中英

SQL Query booking date between from and to

Looking for a sql query that return the data based on the from and to date.

Table :

id - int
carid int,
bookingStartDate - datetime
bookingEndDate - datetime

Here all the following query that i tried to test but all its get fail to retun the expected result

Example 1:

set @startdate='2019-12-21'
set @enddate='2019-12-22'

--Example 1
select  id,bookingStartDate,bookingEndDate from orders
where  
(bookingStartDate between @startdate  and @enddate
and bookingEndDate between @startdate and @enddate)


--Example 2
select  id,bookingStartDate,bookingEndDate from orders
where 
status=4 and 
(bookingStartDate >=@startdate and bookingEndDate <= @enddate)

--Example 3
select  id,bookingStartDate,bookingEndDate from orders
where 
(bookingStartDate <= @startdate  and bookingEndDate >= @startdate)
or 
(bookingStartDate <= @enddate and bookingEndDate >= @enddate)

The requirement is, To check list all available cars based on the from date and todate

This is the overlapping range problem, and your query should look something like this:

SELECT id, bookingStartDate, bookingEndDate
FROM orders
WHERE
    @startdate < bookingEndDate AND
    @enddate   > bookingStartDate;

This would find all available reservations which are able to contain the date range defined by @startdate to @enddate .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM