0

I'm writting a function which at some step I have query result like the following one:

timestamp Consumed Fuel Processed Volume
23-09-2021 5:00:00 3000000 982135
23-09-2021 6:00:00 3000010 982136
23-09-2021 7:00:00 3000030 982137
23-09-2021 8:00:00 3000032 982152

And I have to translate it to this:

timestamp Consumed Fuel Processed Volume
23-09-2021 5:00:00 10 1
23-09-2021 6:00:00 20 2
23-09-2021 7:00:00 2 15

With one row less, and translating the cumulated values to some sort of "rate", subtracting to each row the previous one and labeling it with the previous timestamp. How I could achieve this?

Thanks for your time.

asked Sep 23, 2021 at 8:03
0

1 Answer 1

2

Have a look at window functions in PostgreSQL docs.

lead ( value anyelement [, offset integer [, default anyelement ]] ) → anyelement

Returns value evaluated at the row that is offset rows after the current row within the partition; if there is no such row, instead returns default (which must be of the same type as value). Both offset and default are evaluated with respect to the current row. If omitted, offset defaults to 1 and default to NULL.

SELECT
 tm,
 LEAD(ConsumedFuel) OVER (ORDER BY tm) - ConsumedFuel AS ConsumedFueld,
 LEAD(ProcessedVolume) OVER (ORDER BY tm) - ProcessedVolume AS ProcessedVolume
FROM
 t

db<>fiddle here

answered Sep 23, 2021 at 8:22
7
  • Seems nice, thanks. Would be possible to discard last row? Commented Sep 23, 2021 at 8:37
  • LEAD function is not allowed in WHERE clause. You could add it as subquery. dbfiddle.uk/… Commented Sep 23, 2021 at 8:57
  • I've been tinkering and wouldn't ORDER BY tm DESC OFFSET 1 and then ORDER BY tm ASC be more consistent? Commented Sep 23, 2021 at 13:05
  • Can you add a dbfiddle link please? Commented Sep 23, 2021 at 13:44
  • dbfiddle Commented Sep 23, 2021 at 14:18

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.