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

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

    For similar query I use analytic functions without CTE. Something like:

    select ..., LEAD(gm.id) OVER (ORDER BY Cit DESC) as leadId, LEAD(gm.id, 2) OVER (ORDER BY Cit DESC) as leadId2, LAG(gm.id) OVER (ORDER BY Cit DESC) as lagId, LAG(gm.id, 2) OVER (ORDER BY Cit DESC) as lagId2 ... where id = 25912 or leadId = 25912 or leadId2 = 25912 or lagId = 25912 or lagId2 = 25912

    such query works more faster for me than CTE with join (answer from Scott Bailey). But of course less elegant

提交回复
热议问题