How to get previous row data in sql server

后端 未结 4 1235
青春惊慌失措
青春惊慌失措 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:36

    Use lag() function

    select *, lag(col3) over (partition by col1 order by col2) as col4
    from table t;
    

    However You can also use subquery if your SQL doesn't have LAG()

    select *,   
            (select top 1 col3
             from table
             where col1 = t.col1 and col2 < t.col2
             order by col2 desc
            ) as col4
    from table t;
    

提交回复
热议问题