Create a SQLite view where a row depends on the previous row

前端 未结 4 843
猫巷女王i
猫巷女王i 2020-12-31 20:21

I\'d like to create a view in SQLite where a field in one row depends on the value of a field in the previous row. I could do this in Oracle using the LAG analy

4条回答
  •  既然无缘
    2020-12-31 21:00

    This should do the trick for every item (tested on SQLite):

    SELECT 
        day
        ,price
        ,price - (SELECT t2.price 
                  FROM mytable t2 
                  WHERE 
                      t2.item = t1.item AND 
                      t2.day < t1.day      
                  ORDER BY t2.day DESC
                  LIMIT 1
                 ) AS change
    FROM mytable t1
    

    This assumes the combination between day and item is unique. And the way it works is by taking all the values less than the given day, sorting descending and then LIMIT just the first value, simulating a LAG function.

    For a LEAD behavior, just flip < to > and DESC to ASC.

提交回复
热议问题