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

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

    Its the same idea as the other, but just uses the fields instead of the rowid. This does exactly what you want:

    
    CREATE TABLE Prices (
        day DATE,
        price FLOAT
    );
    
    INSERT INTO Prices(day, price) VALUES(date('now', 'localtime', '+1 day'), 0.5);
    INSERT INTO Prices(day, price) VALUES(date('now', 'localtime', '+0 day'), 1);
    INSERT INTO Prices(day, price) VALUES(date('now', 'localtime', '-1 day'), 2);
    INSERT INTO Prices(day, price) VALUES(date('now', 'localtime', '-2 day'), 7);
    INSERT INTO Prices(day, price) VALUES(date('now', 'localtime', '-3 day'), 8);
    INSERT INTO Prices(day, price) VALUES(date('now', 'localtime', '-4 day'), 10);
    
    SELECT p1.day, p1.price, p1.price-p2.price 
    FROM
        Prices p1, Prices p2,
        (SELECT t2.day AS day1, MAX(t1.day) AS day2 
        FROM Prices t1, Prices t2
        WHERE t1.day < t2.day
        GROUP BY t2.day) AS prev
    WHERE p1.day=prev.day1
        AND p2.day=prev.day2
    
    

    If you want to add the WHERE item='apple' bit you'd add that to both WHERE clauses.

提交回复
热议问题