从sql中的开始日期列表中获取结束日期

时间:2018-10-16 09:28:37

标签: sql sql-server sql-server-2008

我有一个sql查询,可以带回处于特定状态和生效日期的参考(产品)列表。不幸的是,当一种产品变为其他状态时,系统没有输入结束日期,因此我想根据有效日期和序列号生成结束日期。这可能吗?

Product  Status  EffectiveDate          Enddate SeqNo
10      *UC     2017-10-02 00:00:00.000 NULL    8590
584     UC      2017-02-28 00:00:00.000 NULL    8380
584     APA     2017-07-07 00:00:00.000 NULL    8620
584     APA3    2017-08-10 00:00:00.000 NULL    8630
902     *UC     2017-10-13 00:00:00.000 NULL    8590
902     APA     2017-10-13 00:00:00.000 NULL    8620
1017    *UC     2017-09-01 00:00:00.000 NULL    8590
1017    APA     2017-10-10 00:00:00.000 NULL    8620

所以我想返回以下内容...

Product  Status  EffectiveDate          EndDate                     SeqNo
10      *UC     2017-10-02 00:00:00.000 NULL                        8590
584     UC      2017-02-28 00:00:00.000 2017-07-07 00:00:00.000     8380
584     APA     2017-07-07 00:00:00.000 2017-08-10 00:00:00.000     8620
584     APA3    2017-08-10 00:00:00.000 NULL                        8630
902     *UC     2017-10-13 00:00:00.000 2017-10-13 00:00:00.000     8590
902     APA     2017-10-13 00:00:00.000 NULL                        8620
1017    *UC     2017-09-01 00:00:00.000 2017-10-10 00:00:00.000     8590
1017    APA     2017-10-10 00:00:00.000 NULL                        8620

非常感谢。

1 个答案:

答案 0 :(得分:2)

您可以使用lead()

select t.*, lead(EffectiveDate) over (partition by product order by SeqNo) as EndDate
from table t;

但是,lead()2012 +版本开始,因此您可以使用apply来代替:

select t.*, t1.EffectiveDate as EndDate
from table t outer apply
     (select top (1) t1.*
      from table t1
      where t1.product = t.product and t1.SeqNo > t.SeqNo
      order by t1.SeqNo 
     ) t1;
相关问题