I want check date between two dates the record is available or not
Here is the table:
Table1:
S.No StartDate EndDate
-------------------------------------
1. 15/10/2018 20/10/2018
2. 10/10/2018 13/10/2018
3. 21/10/2018 25/10/2018
I need the Output
Five Conditions:
within the date E.g. 17/10/2018 - 19/10/2018
S.No StartDate EndDate
-------------------------------------
1 15/10/2018 20/10/2018
out of the date E.g. 14/10/2018 - 21/10/2018
S.No StartDate EndDate
-------------------------------------
1 15/10/2018 20/10/2018
3 21/10/2018 25/10/2018
Previous from start date E.g. 13/10/2018 - 16/10/2018
S.No StartDate EndDate
-------------------------------------
1 15/10/2018 20/10/2018
2 10/10/2018 13/10/2018
Next from start date E.g. 17/10/2018 - 20/10/2018
S.No StartDate EndDate
-------------------------------------
1 15/10/2018 20/10/2018
another date E.g. 17/11/2018 - 21/11/2018
No records
Here is my idea and my query
SELECT *
FROM Table1
WHERE
CONVERT(DATE, '15/10/2018', 103) BETWEEN StartDate
AND EndDate
AND CONVERT(DATE, '20/10/2018', 103) BETWEEN StartDate
AND EndDate
Thanks in advance
答案 0 :(得分:1)
It looks like you are trying to find date range intersections. But your query finds just date ranges that completely includes your date range parameter. To find the date range intersections you need to change your query to:
SELECT *
FROM table1
WHERE
CONVERT(DATE, '14/10/2018', 103) <= EndDate
AND CONVERT(DATE, '21/10/2018', 103) >= StartDate
if you need all five conditions in a single query without duplicates you can combine it by OR
:
...
WHERE
CONVERT(DATE, '14/10/2018', 103) <= EndDate
AND CONVERT(DATE, '21/10/2018', 103) >= StartDate
OR
CONVERT(DATE, '17/10/2018', 103) <= EndDate
AND CONVERT(DATE, '19/10/2018', 103) >= StartDate
...
If you want all five conditions with duplicates you can use union all
:
SELECT *
FROM table1
WHERE
CONVERT(DATE, '14/10/2018', 103) <= EndDate
AND CONVERT(DATE, '21/10/2018', 103) >= StartDate
UNION ALL
SELECT *
FROM table1
WHERE
CONVERT(DATE, '17/10/2018', 103) <= EndDate
AND CONVERT(DATE, '19/10/2018', 103) >= StartDate
...