I have a (pre-existing, no I did not design it like this!) schema / dataset like this:
CREATE TABLE t(id,name,seq,addon,kind)
AS VALUES
( 1234::int, 'A' , 345::int, 'f'::bool, 'c' ),
( 1235 , NULL, 346 , 't' , NULL ),
( 1236 , NULL, 347 , 't' , NULL ),
( 2345 , 'B' , 348 , 'f' , 'x' ),
( 2346 , NULL, 349 , 't' , NULL ),
( 3456 , 'C' , 350 , 'f' , 'c' ),
( 3457 , NULL, 351 , 't' , NULL );
Where:
- The "id" field is just a SQL sequence (order not guaranteed)
- The "seq" field is guaranteed to be sequential throughout the table, e.g. table is normally sorted on this column.
- The "addon" field is indicating a group of related entries, e.g. TRUE entries are related to the nearest FALSE entry with a lower "seq".
I want to SELECT all the rows with "kind" = 'x' and all of their associated "addon" rows, without getting any other "addon" rows for other kinds.
So for instance:
SELECT * FROM t WHERE kind = 'x' AND ???
Would give me:
id | name | seq |addon | kind |
------+------+------+------+------+...
2345 | "B" | 348 | f | "x" |
2346 | | 349 | t | |
I have PostgreSQL 9.6...