Leonardo M. Ramé-2 wrote > select lag.id, lag.idtask, lag.code, lag.lg from (select idtask, code, id, > lag(code, -1) over () as lg from tasks_test) as lag First you want to include an ORDER BY in the OVER(...) clause, and probably a PARTITION BY as well. Then you move that to a sub-query (for example): SELECT * FROM tbl WHERE tbl.idtask IN ( SELECT lag.idtask FROM ( lag_query_here ) lag WHERE lag.code = 'T' and lag.lg = 'S' ); David J. -- View this message in context: http://postgresql.1045698.n5.nabble.com/Complex-query-tp5798061p5798087.html Sent from the PostgreSQL - general mailing list archive at Nabble.com. -- Sent via pgsql-general mailing list (pgsql-general@xxxxxxxxxxxxxx) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-general