Skip to content
Advertisement

postgresql subtract between row while column shift

I have a simple table like this

I would like to subtract row of yesterday on day(i+1) to row of today on day(i). For example, if today is 2020-01-02 the expected results should be

the 0 (day0) was obtained by 2 (from 2020-01-01 day1) – 2 (from 2020-01-02 day0)
the -2 (day1) was obtained by 1 (from 2020-01-01 day2) – 3 (from 2020-01-02 day1)
the -2 (day2) was obtained by -1 (from 2020-01-01 day3) – 1 (from 2020-01-02 day2)

I’m thinking of select a particular date and its yesterday then transpose and shift row of the yesterday then subtract between 2 transpose column. But i think there might be another elegant way to do. May I have your suggestions?

Advertisement

Answer

You can join the table with itself if you only need to subtract the values for two dates:

This assumes there is actually a previous date for the given date. If there are gaps in the dates, then this would be a bit more complicated.

Online example

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