通过提供 SQL 中的 2 个日期来查找最近的日期范围
Find Closest date range by providing 2 dates in SQL
我正在准备一份包含下表(培训和资源)的 SQL 报告:
Trainings
- Id
- Name
- StartDate
- EndDate
和
Resource
- Id
- FullName
- JoinedOn
- TerminatedOn
我需要的是获得培训期间在那里的资源。例如,我将传递培训 start 和 end 日期,并根据这些日期我需要提取最近的资源:
Training Start Date: 01-08-2017
Training End Date: 04-08-2017
资源
Emp1 (01-05-2016 and 30-09-2017)
Emp2 (01-03-2016 and 30-04-2017)
Emp3 (01-02-2016 and 30-09-2017)
Emp4 (01-08-2017 and 30-04-2018) -- This is the Closest match
Emp5 (01-09-2016 and 30-01-2017)
Emp6 (01-11-2016 and 30-02-2017)
即使其他日期范围也包含这些日期,但 01-08-2016 和 30-04-2017 是最接近的日期.
请帮助我实现这一目标。我尝试了以下方法:
SELECT TOP 1 R.FullName
FROM [Resource] R
WHERE (
(YEAR('01-08-2017') = YEAR(JoinedOn) AND Month('01-08-2017') = Month(JoinedOn) )
OR
(YEAR('04-08-2017') = YEAR(TerminatedOn) AND Month('04-08-2017') = Month(TerminatedOn))
)
ORDER BY TerminatedOn DESC
我想这就是你要的。
declare @resource table
(name varchar(50), joinedon date, terminatedon date)
insert @resource
select 'e1', '2016-5-1', '2017-9-30' union
select 'e2', '2016-3-1', '2017-4-30' union
select 'e3', '2016-2-1', '2017-9-30' union
select 'e4', '2017-8-1', '2018-4-30' union
select 'e5', '2016-9-1', '2017-1-30' union
select 'e6', '2016-11-1', '2017-2-28'
declare @start date= '2017-8-1', @end date = '2017-8-4'
select top 1 *
from @resource r
where joinedon<=@start and terminatedon>=@end
order by datediff(d, @end, terminatedon)+ datediff(d, joinedon, @start)
我正在准备一份包含下表(培训和资源)的 SQL 报告:
Trainings
- Id
- Name
- StartDate
- EndDate
和
Resource
- Id
- FullName
- JoinedOn
- TerminatedOn
我需要的是获得培训期间在那里的资源。例如,我将传递培训 start 和 end 日期,并根据这些日期我需要提取最近的资源:
Training Start Date: 01-08-2017
Training End Date: 04-08-2017
资源
Emp1 (01-05-2016 and 30-09-2017)
Emp2 (01-03-2016 and 30-04-2017)
Emp3 (01-02-2016 and 30-09-2017)
Emp4 (01-08-2017 and 30-04-2018) -- This is the Closest match
Emp5 (01-09-2016 and 30-01-2017)
Emp6 (01-11-2016 and 30-02-2017)
即使其他日期范围也包含这些日期,但 01-08-2016 和 30-04-2017 是最接近的日期.
请帮助我实现这一目标。我尝试了以下方法:
SELECT TOP 1 R.FullName
FROM [Resource] R
WHERE (
(YEAR('01-08-2017') = YEAR(JoinedOn) AND Month('01-08-2017') = Month(JoinedOn) )
OR
(YEAR('04-08-2017') = YEAR(TerminatedOn) AND Month('04-08-2017') = Month(TerminatedOn))
)
ORDER BY TerminatedOn DESC
我想这就是你要的。
declare @resource table
(name varchar(50), joinedon date, terminatedon date)
insert @resource
select 'e1', '2016-5-1', '2017-9-30' union
select 'e2', '2016-3-1', '2017-4-30' union
select 'e3', '2016-2-1', '2017-9-30' union
select 'e4', '2017-8-1', '2018-4-30' union
select 'e5', '2016-9-1', '2017-1-30' union
select 'e6', '2016-11-1', '2017-2-28'
declare @start date= '2017-8-1', @end date = '2017-8-4'
select top 1 *
from @resource r
where joinedon<=@start and terminatedon>=@end
order by datediff(d, @end, terminatedon)+ datediff(d, joinedon, @start)