How to get previous row data in sql server

后端 未结 4 1239
青春惊慌失措
青春惊慌失措 2021-01-20 23:53

I would like to get the data from previous row. I have used LAG function but did not get the expected result.

Table:-

col1  col2  col3
ABCD    1   Y
ABCD         


        
4条回答
  •  春和景丽
    2021-01-21 00:28

    Assuming SQL Server 2012 or newer...

    SELECT
      *,
      LAG(col3) OVER (PARTITION BY col1 ORDER BY col2) AS col4
    FROM
      yourTable
    

    If you're on SQL Server 2008 or older...

    SELECT
      *,
      (
         SELECT TOP(1) previous.col3
           FROM yourTable   AS previous
          WHERE previous.col1 = yourTable.col1
            AND previous.col2 < yourTable.col2
       ORDER BY previous.col2 DESC
      )
        AS col4
    FROM
      yourTable
    

提交回复
热议问题