postgresql-9.3 - 确定 PostgreSQL 中的共轭起始行
问题描述
我正在尝试确定 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')
解决方案
你可以这样做:
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
) 的结果分组,我们将这些日期作为一个组保存在一起。然后最小值和最大值定义连续值列表的开始和结束。然后,have 子句只留下范围大于一天的那些。
然后返回:
id | start_date | end_date
---+------------+-----------
5 | 2018-07-14 | 2018-07-17
推荐阅读
- mysql - SELECT … FOR UPDATE 对不存在的行
- assembly - 寄存器周围的括号是什么意思?
- python - 如何将参数视为函数中的参数(如果可行?)
- python - 如何使用变量名来更新类变量
- ruby-on-rails - Rails has_many 通过特定的 id
- typescript - 将数组映射到具有正确类型的对象(仅类型方式)
- node.js - Azure 应用服务 - 节点应用 - 我需要创建服务器和所需文件吗
- javascript - 子路由未显示在 vuejs 中
- spring - 如何读取/修改通过 Spring Cloud Gateway 的表单数据?
- javascript - 错误:元素类型无效:预期为字符串(对于内置组件)或类/函数(对于复合组件)但得到:未定义