Answer the question
In order to leave comments, you need to log in
How to get the id of the previous record in the selection that met the condition?
Structurally.
CREATE TABLE foo (id int, grp bool);
INSERT INTO foo VALUES (1, false), (2, true), (3, false), (4, false), (5, true), (6, false), (7, false), (8, false);
SELECT * FROM foo ORDER BY id;
id grp
1 false
2 true
3 false
4 false
5 true
6 false
7 false
8 false
id grp grp_id
1 false null
2 true 2
3 false 2
4 false 2
5 true 5
6 false 5
7 false 5
8 false 5
Answer the question
In order to leave comments, you need to log in
https://www.db-fiddle.com/f/cntG2o6N4CXsYxnkrVEAnY/1
Rising High
SELECT *,
max(id) filter ( where grp ) OVER (ORDER BY id) as grp_id
FROM foo
ORDER BY id
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question