How to compare the current row with next and previous row in PostgreSQL?

后端 未结 3 506
谎友^
谎友^ 2020-11-30 00:32

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

3条回答
  •  再見小時候
    2020-11-30 01:22

    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'
    
    • Use two self-joins
    • All words must be in the same sentence (?) and in order.
    • Word before and word after have to be of category 'name'. Word itself not 'name'
    • This assumes that category IS NOT NULL

    To 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:

    • the self joins operate on absolute values: if the row with pos -1 is missing, then the row with pos does not qualify.
    • Renatos version with 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.

提交回复
热议问题