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

后端 未结 5 1842
猫巷女王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:27

    Here's another way to do it with analytic functions lead and lag. It would be nice if we could use analytic functions in the WHERE clause. So instead you need to use subqueries or CTE's. Here's an example that will work with the pagila sample database.

    WITH base AS (
        SELECT lag(customer_id, 5) OVER (ORDER BY customer_id) lag, 
          lead(customer_id, 5) OVER (ORDER BY customer_id) lead, 
          c.*
        FROM customer c
        WHERE c.active = 1
        AND c.last_name LIKE 'B%'
    ) 
    SELECT base.* FROM base 
    JOIN (
      -- Select the center row, coalesce so it still works if there aren't 
      -- 5 rows in front or behind
      SELECT COALESCE(lag, 0) AS lag, COALESCE(lead, 99999) AS lead 
      FROM base WHERE customer_id = 280
    ) sub ON base.customer_id BETWEEN sub.lag AND sub.lead
    

    The problem with sgriffinusa's solution is that you don't know which row_number your center row will end up being. He assumed it will be row 30.

提交回复
热议问题