How can I select adjacent rows to an arbitrary row (in sql or postgresql)?

后端 未结 5 1946
猫巷女王i
猫巷女王i 2021-02-18 17:16

I want to select some rows based on certain criteria, and then take one entry from that set and the 5 rows before it and after it.

Now, I can do this numerically if ther

5条回答
  •  耶瑟儿~
    2021-02-18 17:34

    You could do this utilizing row_number() (available as of 8.4). This may not be the correct syntax (not familiar with postgresql), but hopefully the idea will be illustrated:

    SELECT *
    FROM (SELECT ROW_NUMBER() OVER (ORDER BY primary_key) AS r, *
          FROM table
          WHERE active=1) t
    WHERE 25 < r and r < 35
    

    This will generate a first column having sequential numbers. You can use this to identify the single row and the rows above and below it.

提交回复
热议问题