简体   繁体   English

sql server日期范围条件

[英]sql server date range criteria

I am working on asp.net project. 我正在asp.net项目上。 I have two dates stored in database for a vacancy. 我有两个存储在数据库中的日期空缺。 Posting date and deadline date. 过帐日期和截止日期。 I want that If a user searches for any vacancy with date range then if vacancy's start date or end date falls in that range then it should be selected. 我希望如果用户搜索日期范围内的任何空缺,那么如果空缺的开始日期或结束日期落在该范围内,则应将其选中。 Like if user selects date range March 10 to April 10 and vacancy start date is MArch 1 and deadline date is 20 march then it should be shwon. 例如,如果用户选择日期范围3月10日至4月10日,空缺开始日期为3月1日,截止日期为3月20日,则应该将其设为空。

dummy sql 虚拟SQL

select *
from vacancies v
where v.start date in date range or
      v. end date in date range

What will be sql for it sql将是什么

If you realise that the start date and the deadline just form another range, then this is simply a query to find all overlaps between the user specified range and the vacancy ranges: 如果您意识到开始日期和截止日期只是另一个范围,那么这只是一个查询,用于查找用户指定范围和空缺范围之间的所有重叠:

declare @StartRange datetime
declare @EndRange datetime
select @StartRange='20140310',@EndRange='20140410'

select
    *
from vacancies v
where v.startdate <= @EndRange and
      @StartRange <= v.deadline

(It may need adjustments for <= or < depending on whether you consider either range to have inclusive or exclusive endpoints). (可能需要调整<=<取决于您是否认为范围具有包含端点或排除端点)。

The basic logic is - two ranges overlap if the first range starts before the second one ends, and the second range starts before the first one ends. 基本逻辑是-如果第一个范围在第二个范围结束之前开始, 第二个范围在第一个范围结束之前开始,则两个范围重叠。

This does also pick up eg vacancies which have a start date before the user specified range and a deadline date after the user specified range. 这也确实会出现一些空缺,例如,空缺的开始日期于用户指定的范围,而截止日期早用户指定的范围。 That doesn't match your dummy sql but would usually be desirable (ie the vacancy is open throughout the user specified range) 这与您的虚拟sql不匹配,但通常是理想的(即,在用户指定的整个范围内都空缺了)

You want to do something like: 您想要执行以下操作:

SELECT * 
FROM Vacancies v
WHERE v.StartDate Between @UserProvidedStartDate and @UserProvidedEndDate
   OR v.EndDate Between @UserProvidedStartDate and @UserProvidedEndDate

This assumes you have parameters that are passed with the users search criteria. 假定您具有与用户搜索条件一起传递的参数。

The issue I see with this is that you will return vacancies where the deadline has passed. 我看到的问题是,您将返回截止日期已过去的空缺职位。 If you exclude the vacancy start date from the query, you will only show vacancies where the deadline is within the criteria. 如果您从查询中排除空缺开始日期,则只会显示截止日期在条件内的空缺。 In which case you would just do: 在这种情况下,您只需执行以下操作:

SELECT * 
FROM Vacancies v
WHERE v.EndDate Between @UserProvidedStartDate and @UserProvidedEndDate

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

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