【问题标题】:Get dates with in consecutive 50 days of given date在给定日期的连续 50 天内获取日期
【发布时间】:2018-05-04 23:36:57
【问题描述】:

活动表:

create table #activity(id int, begin_date datetime, end_date datetime)
insert into #activity values(1, '1/1/2017', '1/31/2017')

insert into #activity values(1, '9/1/2017', '9/15/2017')

insert into #activity values(1, '4/1/2017', '4/15/2017')

insert into #activity values(1, '2/5/2017', '2/15/2017')

insert into #activity values(1, '8/1/2017', '8/31/2017')

Insert into #activity values(2, '11/1/2016', '11/15/2016')

现在输入日期是 12/1/2016 和 id,希望在 2016 年 12 月 1 日之后的 50 天内获得所有活动。查询应返回开始日期为 2017 年 1 月 1 日、2017 年 2 月 5 日(因为这是在 2017 年 1 月 31 日的 50 天内)和 2017 年 4 月 1 日的活动。

不应选择 id 1 的 8/1/2017 和 9/1/2017 8/1 不在 4/15 的 50 天内,并且 50 天的周期被打破。

TIA

【问题讨论】:

  • 您的预期结果是什么?
  • 很高兴您将示例数据发布为 DDL+DML。但是,您的问题仍然需要预期的结果以及您当前的尝试。请edit您的问题包括在内。
  • 预期输出为:应返回开始日期为 2017 年 1 月 1 日、2017 年 2 月 5 日(因为这是 2017 年 1 月 31 日的 50 天内)和 2017 年 4 月 1 日的活动.

标签: tsql


【解决方案1】:

OP 说:

希望在 2016 年 12 月 1 日之后的 50 天内获得所有活动

实现该结果的一个可能查询是

-- get all activities with a begin_date within 50 days of input_date
select *
from #activity as a
where @input_date <= a.begin_date and a.begin_date < dateadd(day, 50, @input_date)

但是,OP 然后说:

查询应返回开始日期为 2017 年 1 月 1 日、2017 年 2 月 5 日(因为这是在 2017 年 1 月 31 日之后的 50 天内)和 2017 年 4 月 1 日的活动。 id 1 的 8/1/2017 和 9/1/2017 不应选择 8/1 不在 4/15 的 50 天内,并且 50 天的周期被打破。

这表示您要查找从 2016 年 12 月 1 日开始的所有连续活动,其中连续活动之间的间隔小于 50 天。

一种可能的方法是使用lag 函数。如何在这个问题上使用滞后函数的一个例子是:

select
    a.*
    , lag(a.end_date, 1, @input_date) over (order by a.end_date) as previous_end
    , datediff(day, lag(a.end_date, 1, @input_date)  over (order by a.end_date), a.begin_date) as previous_end_to_this_begin
from #activity as a
where @input_date <= a.begin_date
order by a.begin_date

稍微简化会产生这样的结果:

-- get all activities in a row where the gap between activities is less than 50
select * from #activity as a where @input_date <= a.begin_date and a.begin_date < (
select
    min(a.begin_date) as first_begin_to_not_include
from
    (
        select
            a.begin_date
            , datediff(day, lag(a.end_date, 1, @input_date)  over (order by a.end_date), a.begin_date) as previous_end_to_this_begin
        from #activity as a
        where @input_date <= a.begin_date
    ) as a
where a.previous_end_to_this_begin > 50
)
order by a.begin_date

【讨论】:

    猜你喜欢
    • 2017-09-18
    • 2013-08-30
    • 2020-08-24
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多