我想找到工期。我想为每个学生ID获取该状态的min(lastupdatedate),并从该状态的下一个min(lastupdatedate)中减去。如果没有下一个状态可用,那么我们必须考虑getdate()。如果对于给定的Studentid我只有1个状态,则min(lastupdatedate)-getdate()
CREATE TABLE mytable
(
id INT IDENTITY(1,1),
studentid int NOT NULL,
status VARCHAR(7),
createddate DATE,
lastupdatedate DATE,
durationdays INT NULL
);
INSERT INTO mytable(studentid, status, createddate, lastupdatedate)
VALUES
(1,'New','2/15/2019','2/15/2019')
,(1,'Open','2/15/2019','2/25/2019')
,(1,'Sub','2/15/2019','3/17/2019')
,(1,'PS','2/15/2019','3/27/2019')
,(1,'PI','2/15/2019','5/11/2019')
,(1,'PR','2/15/2019','5/15/2019')
,(1,'PI','2/15/2019','5/27/2019')
,(1,'PC','2/15/2019','8/25/2019')
,(1,'PI','2/15/2019','9/4/2019')
,(1,'PI','2/15/2019','10/24/2019')
,(1,'PC','2/15/2019','11/5/2019')
,(1,'RC','2/15/2019','11/16/2019') ;
输出量
studentid status createddate lastupdatedate duration_days
--------------------------------------------------------------------
1 New 2019-02-15 2019-02-15 10
1 Open 2019-02-15 2019-02-25 20
1 Sub 2019-02-15 2019-03-17 10
1 PS 2019-02-15 2019-03-27 45
1 PI 2019-02-15 2019-05-11 4
1 PR 2019-02-15 2019-05-15 12
1 PI 2019-02-15 2019-05-27 90
1 PC 2019-02-15 2019-08-25 10
1 PI 2019-02-15 2019-09-04 50
1 PC 2019-02-15 2019-11-05 11
1 RC 2019-02-15 2019-11-16 34
但是,此查询执行了您上面的要求,在没有奇数个日期时间的结果中没有滞后日期时,减去了GETDATE()。
DECLARE @GetDate DATETIME ='02/05/2019'
SELECT
id,studentid,status,createddate,
lastupdatedate,
NextLastModifiedDateByStudentStatus = LEAD(lastupdatedate) OVER(PARTITION BY studentid,status ORDER BY lastupdatedate),
derivednextupdatedate= ISNULL(LEAD(lastupdatedate) OVER(PARTITION BY studentid,status ORDER BY lastupdatedate),@GetDate),
daysapart = ABS(DATEDIFF(DAY,ISNULL(LEAD(lastupdatedate) OVER(PARTITION BY studentid,status ORDER BY lastupdatedate),@GetDate),lastupdatedate))
FROM
@mytable
ORDER BY
studentId, status, lastupdatedate
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。