P
P
pqgg7nwkd42020-11-02 12:30:32
PostgreSQL
pqgg7nwkd4, 2020-11-02 12:30:32

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);

grp is a kind of condition.
We get the following sample:
SELECT * FROM foo ORDER BY id;
id	grp
1	false
2	true
3	false
4	false
5	true
6	false
7	false
8	false

And you need to get grp_id ⸺ id of the previous entry, where grp=true:
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

Sandbox: https://www.db-fiddle.com/f/cntG2o6N4CXsYxnkrVEAnY/0

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
pqgg7nwkd4, 2020-11-02
@pqgg7nwkd4

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 question

Ask a Question

731 491 924 answers to any question