【发布时间】:2021-04-14 11:43:53
【问题描述】:
我有一个带有部分连续整数 id 的表,即有诸如 1,2,3, 6,7,8, 10, 23,24,25,26 之类的块。
- 间隙大小是动态的
- 块的长度是动态的
我对从表格中选择的简单解决方案感到头疼 并包含一列,其中值对应于相应块的第一个 id。
即像这样的
select id, first(id) over <what goes here?> first from table;
结果应该如下所示
| id | first |
|----|-------|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 6 | 6 |
| 7 | 6 |
| 8 | 6 |
| 10 | 10 |
| 23 | 23 |
| 24 | 23 |
| 25 | 23 |
| 26 | 23 |
之后我可以将此列与partition by 窗口函数子句很好地结合使用。
到目前为止,我想出的总是与此类似,但没有成功:
WITH foo AS (
SELECT LAG(id) OVER (ORDER BY id) AS previous_id,
id AS id,
id - LAG(id, 1, id) OVER (ORDER BY id) AS first_in_sequence
FROM table)
SELECT *,
FIRST_VALUE(id) OVER (ORDER BY id) AS first
FROM foo
ORDER BY id;
定义一个自定义的 postgres 函数也是一个可接受的解决方案。
感谢您的建议,
马蒂
【问题讨论】:
标签: postgresql aggregate-functions window-functions