简体   繁体   English

如何在 sql 中的日期范围之间获取数据

[英]How to get data between a range of dates in sql

I need to select records between the dates:我需要在日期之间记录 select :

在此处输入图像描述

If I input BeginDate as 5/Jan/2019 18:40:00 and EndDate as 25/Jan/2019 18:40:00 then both rows must be selected.如果我将 BeginDate 输入为 5/Jan/2019 18:40:00 并将 EndDate 输入为 25/Jan/2019 18:40:00,则必须选择这两行。

Another example... a record's BeginDate and EndDate respectively 1/Jan/2019 and 31/Jan/2019.另一个例子……记录的 BeginDate 和 EndDate 分别是 1/Jan/2019 和 31/Jan/2019。 If I input 5/Jan/2019 and 25/Jan/2019 then that record must be selected.如果我输入 2019 年 1 月 5 日和 2019 年 1 月 25 日,则必须选择该记录。

Think is if I input any dates between the actual Begindate and EndDate of the records that should be selected.想想如果我在应该选择的记录的实际开始日期和结束日期之间输入任何日期。

I used between but it selecting the records having the exact date values.我使用了 between,但它选择了具有确切日期值的记录。

BeginDate >= @BeginDate 
and BeginDate <= dateadd(day, 1, @EndDate)
and (EndDate is null or EndDate> @EndDate)

Can anyone help me to fix this.谁能帮我解决这个问题。

Based on your feedback, you need a simple date overlap query:根据您的反馈,您需要一个简单的日期重叠查询:

SELECT *
FROM t
WHERE @EndDate   > BeginDate
AND   @BeginDate < EndDate

It will match the rows where the Start and EndDate intersect @Start and @EndDate in any manner.它将匹配 Start 和 EndDate 以任何方式与 @Start 和 @EndDate 相交的行。 It assumes that end dates are exclusive.它假定结束日期是唯一的。 You might want to add (... OR EndDate IS NULL) to handle null values.您可能想要添加(... OR EndDate IS NULL)来处理 null 值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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