I want to know how to retrieve results in a SQL query doing some logic comparison with the next or previous rows. I\'m using PostgreSQL.
Example
This should work:
SELECT w1.word AS word_before, w.word, w2.word AS word_after
FROM word w
JOIN word w1 USING (sentence)
JOIN word w2 USING (sentence)
WHERE w.category <> 'name'
AND w1.pos = (w.pos - 1)
AND w1.category = 'name'
AND w2.pos = (w.pos + 1)
AND w2.category = 'name'
IS NOT NULLTo answer your additional question: no, a window function would not be particularly useful in this case, self-join is the magic word here.
Edit:
I stand corrected. Renato demonstrates a cool solution with the window functions lag() and lead().
Note the subtle differences:
pos -1 is missing, then the row with pos does not qualify.lag() and lead() operates on the relative position of rows created by ORDER BY.In many cases (like probably in the one at hand?) both versions lead to identical results. With gaps in the id space there will be different results.