提问人:Massey 提问时间:2/8/2022 最后编辑:Kazi Mohammad Ali Nur RomelMassey 更新时间:2/8/2022 访问量:269
如何查找表是否具有给定的日期范围
How to find whether a table has a given date range
问:
我想了解表中是否有行在传递给查询的日期范围内。以下是 中的数据。我正在使用 SQL ServerMYTABLE
DISPLAY_START_DATE DISPLAY_END_DATE
2022-02-02 00:00:00.000 2022-02-28 00:00:00.000
2022-02-02 00:00:00.000 2022-02-06 10:34:01.653
2022-02-01 00:00:00.000 2022-02-17 00:00:00.000
2022-02-07 00:00:00.000 2022-02-25 00:00:00.000
以下是我的查询
DECLARE @startdate AS datetime ='2022-02-01'
DECLARE @enddate AS datetime ='2022-02-10'
SELECT * from MYTABLE mt
WHERE
(mt.DISPLAY_START_DATE = @startdate and mt.DISPLAY_END_DATE = @enddate) OR
(mt.DISPLAY_START_DATE < @startdate and mt.DISPLAY_END_DATE > @enddate) OR
(mt.DISPLAY_START_DATE < @startdate and mt.DISPLAY_END_DATE < @enddate) OR
(mt.DISPLAY_START_DATE < @startdate and mt.DISPLAY_END_DATE < @enddate and
mt.DISPLAY_END_DATE > @startdate) OR
(mt.DISPLAY_START_DATE > @startdate and mt.DISPLAY_END_DATE < @enddate) OR
(mt.DISPLAY_START_DATE > @startdate and mt.DISPLAY_START_DATE < @enddate and
mt.DISPLAY_END_DATE < @enddate)
这将仅拉取与以下数据对应的第二行
DISPLAY_START_DATE DISPLAY_END_DATE
2022-02-02 00:00:00.000 2022-02-06 10:34:01.653
答:
1赞
Serg
2/8/2022
#1
两个区间相交条件是每个区间必须在另一个区间结束之前开始:
..
WHERE mt.DISPLAY_START_DATE <= @enddate AND @startdate <= mt.DISPLAY_END_DATE
0赞
Kazi Mohammad Ali Nur Romel
2/8/2022
#2
如果要选择在给定范围内同时具有两个日期的所有行,可以尝试以下查询:
DECLARE @startdate AS datetime ='2022-02-01'
DECLARE @enddate AS datetime ='2022-02-10'
SELECT * from MYTABLE mt
WHERE
(mt.DISPLAY_START_DATE between @startdate and @enddate and mt.DISPLAY_END_DATE between @startdate and @enddate)
或者,如果您希望 where 条件从表中选择全部或部分在范围内的所有行
SELECT * from MYTABLE mt
WHERE
(mt.DISPLAY_START_DATE between @startdate and @enddate and mt.DISPLAY_END_DATE between @startdate and @enddate) or
(mt.DISPLAY_START_DATE <=@startdate and mt.DISPLAY_END_DATE >=@enddate) or
(mt.DISPLAY_START_DATE <=@startdate and mt.DISPLAY_END_DATE between @startdate and @enddate) or
(mt.DISPLAY_START_DATE between @startdate and @enddate and mt.DISPLAY_END_DATE >=@enddate)
评论
0赞
Massey
2/8/2022
谢谢卡兹。我已经使用了你的第二个解决方案。它工作得很完美!
0赞
Kazi Mohammad Ali Nur Romel
2/8/2022
非常欢迎您。愿你安好。
评论