找到下一行的时差

时间:2013-06-27 00:19:07

标签: sql postgresql window-functions

如何查找具有不同源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 

如何区分第一条记录的EndDate与下一条记录的开始日期之间的差异,以及不同的源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

1 个答案:

答案 0 :(得分: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)