T-SQL:基于开/关列的组日期范围和设置结束日期

时间:2017-06-09 18:26:12

标签: sql-server tsql

我很难找到一种有效,简洁的方法,没有循环来生成活动日期组,其中活动(授予/撤消活动)基于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-06-06,这将成为跨度的结束日期。

更重要的是,日期也应按活动跨度进行分组。如果在这里有另一年的记录,则需要在另一行。

我可以请一些查询来帮助解决这个问题吗?

1 个答案:

答案 0 :(得分:3)

这是你想要的吗?

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;

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