我的记录如下
StartDate | EndDate | ID
---------------------------------
25-12-2016 30-12-2016 0
01-01-2017 05-01-2017 1
10-01-2017 12-01-2017 2
01-02-2017 05-02-2017 3
通过从 02-01-2017 选择日期范围直到 11-01-2017 ,我们如何选择介于两者之间的记录Startdate n EndDate按预期给出的日期范围?
希望表格结果如下
StartDate | EndDate | ID
------------------------------
01-01-2017 05-01-2017 1
10-01-2017 12-01-2017 2
答案 0 :(得分:2)
所以,基本上你问的是如何检查两个日期范围是否重叠。 这样做的方法是检查一个在另一个结束之前开始,而另一个在结束之前开始。您可以在overlap tag wiki.
中查看可视化效果您的查询应该是这样的:
SELECT StartDate, EndDate, ID
FROM YourTable
WHERE StartDate <= '11-01-2017'
AND EndDate >= '02-01-2017'
答案 1 :(得分:0)
尝试以下查询,
DECLARE @V_START_DATE DATETIME = '2017-01-02'
,@V_END_DATE DATETIME = '2017-01-11'
SELECT *
FROM @TABLE
WHERE StartDate BETWEEN @V_START_DATE AND @V_END_DATE
OR EndDate BETWEEN @V_START_DATE AND @V_END_DATE
答案 2 :(得分:0)
尝试以下查询
SELECT * FROM DateRanges
WHERE StartDate BETWEEN '02-01-2017' and '11-01-2017'
OR ENDdate BETWEEN '02-01-2017' and '11-01-2017'