PostgreSQL calculate difference between rows

SqlPostgresql

Sql Problem Overview


I tried to calculate difference between rows in a field using a query:

Illustrations:
input:year,month,fixes
output:increase

 year | month | fixes    | increase
------+-------+----------+-----------
 2006 | 04    |       1  | 0
 2006 | 05    |       4  | 3
 2006 | 06    |       3  | -1

Increase column as output by difference between adjacent rows in fixes.

Sql Solutions


Solution 1 - Sql

This is what window functions are for:

select year, 
       month,
       fixes,
       fixes - lag(fixes) over (order by year, month) as increase,
from the_table;

For more details please see the manual:
http://www.postgresql.org/docs/current/static/tutorial-window.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2177232View Question on Stackoverflow
Solution 1 - Sqla_horse_with_no_nameView Answer on Stackoverflow