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

前端 未结 4 840
猫巷女王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:24

    Assuming that you don't delete this will work:

    
    SELECT t2.DAY, t2.price, t2.price-t1.price 
    FROM TABLENAME t1, TABLENAME t2 
    WHERE t1.rowid=t2.rowid-1
    

    This works because every row has its own rowid even if you dont specify it in the CREATE statement.

    If you do delete, it becomes:

    
    SELECT t2.day, t2.price, t2.price-t1.price 
    FROM 
         (SELECT l1.day, l1.price, 
              (SELECT COUNT(*) 
              FROM TABLENAME l2 
              WHERE l2.rowid < l1.rowid) AS count
          FROM TABLENAME l1) AS t1,
         (SELECT l1.day, l1.price, 
              (SELECT COUNT(*) 
              FROM TABLENAME l2 
              WHERE l2.rowid < l1.rowid) AS count
          FROM TABLENAME l1) AS t2
    WHERE t1.count=t2.count-1
    

    This works under the assumption that rowids are always increasing.

提交回复
热议问题