Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare value between current date and yesterday on the same table POSTGRESQL

I have a table like this:

product value trx_date
apple 100 2020-06-01
apple 300 2020-06-02
apple 500 2020-06-03

and I need create a report like this (let's say today is 2020-06-03)

product yesterday current_date delta
apple 300 500 200

I'm confused how to create a query (PostgreSQL), comparing those values. fyi, i always update this table every day. I tried with ('1 day'::interval) query but it always shows all dates before 2020-06-03 which is 2020-06-01 and 2020-06-02...

like image 240
nadegnaro Avatar asked Feb 20 '26 20:02

nadegnaro


1 Answers

Use the Window Function lead or lag to 'combine' data to the current row from following rows (lead) or previous rows (lag). In this case the I use the lag function to get "yesterdays" value.

select product, yesterday,  today, today-yesterday delta
  from ( select p.product, p.value today 
              , lag(value) over (partition by p.product 
                                     order by p.trx_date) yesterday
              , p.trx_date
          from products p
       ) d
 where trx_date = '2020-06-03'::date ;        
like image 127
Belayer Avatar answered Feb 22 '26 15:02

Belayer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!