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

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

    If you wanted to do it in a 'relationally pure' way, you could write a query that sorted and numbered the rows. Like:

    select (
      select count(*) from employees b
      where b.name < a.name
    ) as idx, name
    from employees a
    order by name
    

    Then use that as a common table expression. Write a select which filters it down to the rows you're interested in, then join it back onto itself using a criterion that the index of the right-hand copy of the table is no more than k larger or smaller than the index of the row on the left. Project over just the rows on the right. Like:

    with numbered_emps as (
      select (
        select count(*)
        from employees b
        where b.name < a.name
      ) as idx, name
      from employees a
      order by name
    )
    select b.*
    from numbered_emps a, numbered_emps b
    where a.name like '% Smith' -- this is your main selection criterion
    and ((b.idx - a.idx) between -5 and 5) -- this is your adjacency fuzzy-join criterion
    

    What could be simpler!

    I'd imagine the row-number based solutions will be faster, though.

提交回复
热议问题