【问题标题】:T-SQL: group date ranges and set end date based on, on/off columnT-SQL:分组日期范围并根据开/关列设置结束日期
【发布时间】:2017-06-10 11:13:08
【问题描述】:

我正在努力寻找一种没有循环的有效、简洁的方法来生成活动日期组,其中活动(授予/撤销活动)基于 Switch 列,其值为 0 关闭和 1 开启以及开始和结束日期.

TransactionDate    EffectiveDate    TerminationDate    Switch
-------------------------------------------------------------------
2013-06-14         2013-05-29       NULL               1
2013-06-14         2013-06-05       2013-06-05         0
2013-10-03         2013-05-29       2013-05-29         0
2013-10-12         2013-05-29       NULL               1
2013-10-12         2013-06-06       2013-06-06         0

最终输出应该只有一行:

2013-05-29 to 2013-06-06

输出是一行,因为最后两个事务在 2013 年 5 月 29 日开启,而最后一次关闭是在 2013 年 6 月 6 日,这成为跨度的结束日期。

此外,日期还应按活动跨度分组。如果这里还有其他年份记录,则需要单独放置一行。

我能否获得一些帮助以解决此问题?

【问题讨论】:

    标签: sql-server tsql


    【解决方案1】:

    这是你想要的吗?

    select max(case when switch = 1 then effective_date end) as on_date,
           (case when max(case when switch = 1 then effective_date end) <
                      max(case when switch = 0 then effective_date end)
                 then max(case when switch = 0 then effective_date end)
            end) as off_date  -- if any
    from t;
    

    这将获取开关打开的最后日期。然后最后一个日期关闭。

    【讨论】:

    • 是的,只需删除最后一个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 2019-03-20
    相关资源
    最近更新 更多