I have a simple table like this
date day0 day1 day2 day3 2020-01-01 3 2 1 -1 2020-01-02 2 3 1 0 2020-01-03 4 1 -1 2 2020-01-04 5 2 0 1
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
date day0 day1 day2 day3 2020-01-02 0 -2 -2 NaN
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:
select t.date, y.day0 - t.day0 as day0, y.day2 - t.day1 as day1, y.day3 - t.day2 as day2, 'NaN'::numeric as day3 from data t join data y on y.date = t.date - 1 -- join to the previous date where t.date = date '2020-01-02'; -- or replace with t.date = current_date
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.