Skip to content
Advertisement

Finding last and second last date and corresponding values

Consider the following schema (fiddle):

For each meter.id I need to find the latest reading date, value, and the value difference vs previous reading.

For the sample data my output would look like this (plus some other columns from meters):

meterid latest value delta value
1 20090403 399 99
2 20090403 288 44
3 20090403 555 null
4 20090303 600 50
5 null null null

I figured I could first create a query with the relevant info and then join with that, but I struggle with achieving that

I’ve tried to adapt this method but for each id I get 2 rows instead of one

I’m looking for ideas how to solve the double row issue, or if that’s a dead end how to get my desired output

Advertisement

Answer

If I understand correctly, you can just use window functions:

No aggregation is necessary. Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement