开发者社区> 问答> 正文

SQL Server:从该id的每个状态获取min(lastupdatedate)

我想找到工期。我想为每个学生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

展开
收起
祖安文状元 2020-01-05 14:08:27 463 0
1 条回答
写回答
取消 提交回答
  • 但是,此查询执行了您上面的要求,在没有奇数个日期时间的结果中没有滞后日期时,减去了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
    
    2020-01-05 14:08:46
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
SQL Server在电子商务中的应用与实践 立即下载
GeoMesa on Spark SQL 立即下载
原生SQL on Hadoop引擎- Apache HAWQ 2.x最新技术解密malili 立即下载