【问题标题】:Find Closest date range by providing 2 dates in SQL通过在 SQL 中提供 2 个日期来查找最近的日期范围
【发布时间】:2018-01-04 09:37:07
【问题描述】:

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

Trainings
- Id
- Name
- StartDate
- EndDate

还有

Resource
- Id
- FullName
- JoinedOn
- TerminatedOn

我需要的是在培训期间获得资源。例如,我将传递培训 startend 日期,并根据这些日期提取最近的资源:

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-201630-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

【问题讨论】:

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


    【解决方案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) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 2020-05-23
      相关资源
      最近更新 更多