[英]get end dates from list of start dates in sql
I have a sql query that brings back a list of references (products) that were at a specific status and an effective date. 我有一个SQL查询,可带回处于特定状态和生效日期的参考(产品)列表。 Unfortunately when one product moves to a different status the system doesn't put an end date in, so I am wanting to generate the end date, based on the effective date and sequence number.
不幸的是,当一种产品变为其他状态时,系统没有输入结束日期,因此我想根据有效日期和序列号生成结束日期。 Is this possible?
这可能吗?
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
SO I would want to return the following... 所以我想返回以下内容...
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
Many thanks. 非常感谢。
You can use lead()
: 您可以使用
lead()
:
select t.*, lead(EffectiveDate) over (partition by product order by SeqNo) as EndDate
from table t;
However, lead()
starts from version 2012 +
, so you can use apply
instead : 但是,
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.