确定PostgreSQL中的共轭起始行

问题描述 投票:0回答:1

我正在尝试确定PostgreSQL中的共形起始行

我的表名emp具有两列id(integer)和entry_date(date)。像这样的记录

ID  |  entry_date 
----+-------------
1   |  2018-05-03 
5   |  2018-06-10 
6   |  2018-06-11 
1   |  2018-07-13 
5   |  2018-07-14 
5   |  2018-07-15 
5   |  2018-07-16 
5   |  2018-07-17 

现在我想找出开始的共轭记录(5, '2018-07-14')和结束的记录(5, '2018-07-17')

postgresql-9.3 gaps-and-islands
1个回答
0
投票

您可以执行以下操作:

select id, min(entry_date) as start_date, max(entry_date) as end_date
from (
  select id, 
         entry_date, 
         entry_date - (row_number() over(partition by id order by entry_date))::int as grp
  from the_table
) t
group by id, grp
having max(entry_date) - min(entry_date) > 1
order by id, grp

表达式entry_date - (row_number() over(partition by id order by entry_date))::int为所有连续的“组”创建一个DATE值。因此内部查询返回以下结果(基于您的示例数据):

id | entry_date | grp       
---+------------+-----------
 1 | 2018-05-03 | 2018-05-02
 1 | 2018-07-13 | 2018-07-11
 5 | 2018-06-10 | 2018-06-09
 5 | 2018-07-14 | 2018-07-12
 5 | 2018-07-15 | 2018-07-12
 5 | 2018-07-16 | 2018-07-12
 5 | 2018-07-17 | 2018-07-12
 6 | 2018-06-11 | 2018-06-10

通过将当天的结果分组(grp),我们将这些日期作为一个单独的组一起保存。然后,最小值和最大值定义连续值列表的开始和结束。然后,having子句只保留范围大于一天的那些。

然后返回:

id | start_date | end_date  
---+------------+-----------
 5 | 2018-07-14 | 2018-07-17

Online example

© www.soinside.com 2019 - 2024. All rights reserved.