Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL calculate difference between rows

Tags:

sql

postgresql

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.

like image 991
user2177232 Avatar asked Jul 11 '14 06:07

user2177232


People also ask

How do you calculate row difference?

Method 1 : Using diff() method diff() method in base R is used to find the difference among all the pairs of consecutive rows in the R dataframe. It returns a vector with the length equivalent to the length of the input column – 1.

How do I find the difference between two rows in SQL?

In the blue text, you can see the calculation of the SQL delta between two rows. To calculate a difference, you need a pair of records; those two records are “the current record” and “the previous year's record”. You obtain this record using the LAG() window function.

How do you do a difference in in PostgreSQL?

Discussion: To calculate the difference between the timestamps in PostgreSQL, simply subtract the start timestamp from the end timestamp. Here, it would be arrival - departure . The difference will be of the type interval , which means you'll see it in days, hours, minutes, and seconds.

How do I find the difference between two tables in PostgreSQL?

col = tbl1. col); If you don't know which table has surplus rows or both have, you can either repeat the above query after switching table names, or: SELECT * FROM tbl1 FULL OUTER JOIN tbl2 USING (col) WHERE tbl2 col IS NULL OR tbl1.


1 Answers

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

like image 112
a_horse_with_no_name Avatar answered Oct 10 '22 10:10

a_horse_with_no_name