Re: obtain the difference between successive rows

From: Thalis Kalfigkopoulos <tkalfigo(at)gmail(dot)com>
To: btober(at)computer(dot)org
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: obtain the difference between successive rows
Date: 2012-10-20 15:54:11
Message-ID: CAEkCx9FHeMzQW+7oTTKqVR=vQ-xACq_G9oLNJ9ZQ9EV21AVkbQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

> What about if there is more than one column you want the difference for (...
> coincidentally I am writing a article on this topic right now! ...), say a
> table which is used to record a metered quantity at not-quite regular
> intervals:
>
> CREATE TABLE electricity
> (
> current_reading_date date,
> current_meter_reading integer
> );
>
>
> with sample data:
>
>
> '2012-09-07',2158
> '2012-10-05',3018
>
>
>
> and I want an output such as:
>
>
> Meter Read on October 5
>
> Current Previous kWh
> Reading Reading Used
> -----------------------------------
> 3018 - 2158 = 860
>
> Number service days = 28

No problem with that either.
$ SELECT current_meter_reading - lag(current_meter_reading) OVER(ORDER
BY current_reading_date) AS kWh_diff, extract('days' FROM
current_reading_date - lag(current_reading_date) OVER(ORDER BY
current_reading_date)) as num_service_days FROM mytable;

Note how ORDER BY is in both cases done by current_reading_date. This
is because the current_reading_date defines the concept of
previous/next row whose values (either current_meter_reading or
current_reading_date) I want to be comparing.

regards,
Thalis

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Berend Tober 2012-10-20 16:02:49 Re: obtain the difference between successive rows
Previous Message Chris Angelico 2012-10-20 15:42:37 Re: obtain the difference between successive rows