Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sqlite subtract different rows from different columns

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading