通过在SQL

时间:2018-01-04 09:37:07

标签: sql sql-server date sql-order-by

我正在准备一份包含以下表格的SQL报告(培训和资源):

Trainings
- Id
- Name
- StartDate
- EndDate

并且

Resource
- Id
- FullName
- JoinedOn
- TerminatedOn

我需要的是获取培训期间所在的资源。例如,我将通过培训开始结束日期,并根据这些日期我需要提取最近资源:

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

1 个答案:

答案 0 :(得分:1)

我认为这就是你所要求的。

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) 
相关问题