Home > Software design >  Sqlite subtract different rows from different columns
Sqlite subtract different rows from different columns

Time:12-20

Let's say that I have sql table like this:

id | val_1 | val_2
1  | 55    |  300
2  | 90    |  600
3  | 80    |  200
..

Now, I wan't to subtract 300-90, and next 600-80 and so on with offset of one row. Table can be odd count like this. Is there a chance to do this without loop and external functions? I use Python api for sqlite3.

Thanks in advance!

CodePudding user response:

Depending on the output that you want you can use LEAD() window function:

SELECT *, 
       val_2 - LEAD(val_1, 1, 0) OVER (ORDER BY id) AS difference
FROM tablename;

or LAG() window function:

SELECT *, 
       LAG(val_2, 1, 0) OVER (ORDER BY id) - val_1 AS difference
FROM tablename;

See the demo.

  • Related