1

如何查找具有不同源 ID 的不同列之间的时间差(以分钟为单位)

No SourceID  RecordID  Start Date               End Date
1  1         1         2009-09-07 09:12:00.0000 2009-09-07 11:00:00.0000 
2  1         1         2009-09-07 11:19:00.0000 2009-09-07 12:12:00.0000  
3  1         1         2009-09-07 12:23:00.0000 2009-09-07 12:54:00.0000  
4  1         1         2009-09-07 13:49:00.0000 2009-09-07 14:45:00.0000 
5  2         2         2009-10-12 09:12:00.0000 2009-10-12 11:00:00.0000  
6  2         2         2009-10-12 11:19:00.0000 2009-10-12 12:12:00.0000
7  2         2         2009-10-12 12:23:00.0000 2009-10-12 12:54:00.0000 

如何获取第一条记录的结束日期与下一条记录的开始日期与不同源 ID 相同的差异以及如何用“-1”填充空白空间然后更新为一列?

这里的结果需要得到

 SourceID  RecordID  Start Date               End Date                 DiffMin
 1         1         2009-09-07 09:12:00.0000 2009-09-07 11:00:00.0000 19 
 1         1         2009-09-07 11:19:00.0000 2009-09-07 12:12:00.0000 11 
 1         1         2009-09-07 12:23:00.0000 2009-09-07 12:54:00.0000 55 
 1         1         2009-09-07 13:49:00.0000 2009-09-07 14:45:00.0000 NULL
 2         2         2009-10-12 09:12:00.0000 2009-10-12 11:00:00.0000 19 
 2         2         2009-10-12 11:19:00.0000 2009-10-12 12:12:00.0000 11
 2         2         2009-10-12 12:23:00.0000 2009-10-12 12:54:00.0000 55
4

1 回答 1

4

可能想要使用以下几行的分析函数:

postgres=# SELECT No, SourceID, RecordID, StartDate, EndDate
postgres-#       ,LEAD(StartDate) OVER(PARTITION BY SourceID ORDER BY StartDate) - EndDate AS diff
postgres-#   FROM myTable;
 no | sourceid | recordid |      startdate      |       enddate       |   diff
----+----------+----------+---------------------+---------------------+-----------
  1 |        1 |        1 | 2009-09-07 09:12:00 | 2009-09-07 11:00:00 |  00:19:00
  2 |        1 |        1 | 2009-09-07 11:19:00 | 2009-09-07 12:12:00 |  00:11:00
  3 |        1 |        1 | 2009-09-07 12:23:00 | 2009-09-07 12:54:00 |  00:55:00
  4 |        1 |        1 | 2009-09-07 13:49:00 | 2009-09-07 14:45:00 |
  5 |        2 |        2 | 2009-10-12 09:12:00 | 2009-10-12 11:00:00 |  00:19:00
  6 |        2 |        2 | 2009-10-12 11:19:00 | 2009-10-12 12:12:00 |  00:11:00
  7 |        2 |        2 | 2009-10-12 12:23:00 | 2009-10-12 12:54:00 |
(7 rows)
于 2013-06-27T00:34:03.167 回答