我尝试编写查询以根据一个字段选择连续块,将其转换为状态更改记录。基本上我只需要选择一个" v1"如果在基于id排序时多次出现相同的值。 让我们假设下表:
| id | v1 | v2 | v3 |
---------------------
|1 | a | b | b |
|2 | a | e | b |
|3 | z | b | b |
|4 | z | o | p |
|5 | a | h | t |
|6 | a | i | k |
|7 | b | g | p |
期望的结果:
|time sequence | state |
----------------------------
|1 | a |
|2 | z |
|3 | a |
|4 | b |
任何人都有什么想法?
答案 0 :(得分:2)
在这种情况下使用window function,lag()
。
此查询查找系列的开头:
select id, v1, v1 is distinct from lag(v1) over (order by id) as start
from my_table
id | v1 | start
----+----+-------
1 | a | t
2 | a | f
3 | z | t
4 | z | f
5 | a | t
6 | a | f
7 | b | t
(7 rows)
仅选择start = true
行并添加行号:
select row_number() over (order by id) as sequence, v1 as state
from (
select id, v1, v1 is distinct from lag(v1) over (order by id) as start
from my_table
) s
where start
sequence | state
----------+-------
1 | a
2 | z
3 | a
4 | b
(4 rows)