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

后端 未结 3 503
谎友^
谎友^ 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:31

    You can find the best solution in this address:

    http://blog.sqlauthority.com/2013/09/25/sql-server-how-to-access-the-previous-row-and-next-row-value-in-select-statement-part-4/

    Query 1 for SQL Server 2012 and later version:

    SELECT
    LAG(p.FirstName) OVER(ORDER BY p.BusinessEntityID) PreviousValue,
        p.FirstName,
        LEAD(p.FirstName) OVER(ORDER BY p.BusinessEntityID) NextValue
    FROM Person.Person p
    GO
    

    Query 2 for SQL Server 2005+ and later version:

    WITH CTE AS(
        SELECT rownum = ROW_NUMBER() OVER(ORDER BY p.BusinessEntityID),
        p.FirstName FROM Person.Person p
    )
    SELECT
    prev.FirstName PreviousValue,
        CTE.FirstName,
        nex.FirstName NextValue
    FROM CTE
    LEFT JOIN CTE prev ON prev.rownum = CTE.rownum - 1
    LEFT JOIN CTE nex ON nex.rownum = CTE.rownum + 1
    GO
    

提交回复
热议问题