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

Viewed 517

First of all, i hope you guys understand my poor english :))

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 (lets say today is 2020-06-03)
product | yesterday | current_date | delta
apple    | 300           | 500               | 200

im confused how to create a query (postgre), comparing those value.. fyi, i always update this table everyday.. i tried with ('1 day'::interval) query but it always show all date before 2020-06-03 which is 2020-06-01 and 2020-06-02..

i appreciate for your help..

2 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 ;        

Using CTE:

https://www.postgresql.org/docs/12/queries-with.html

An example:

CREATE TABLE product_table (product varchar, value integer, trx_date date);
INSERT INTO product_table values ('apple', 100, '06/01/2020'), ('apple', 300, '06/02/2020'), ('apple', 500, '06/03/2020');

WITH prev AS (
    SELECT
        product,
        value
    FROM
        product_table
    WHERE
        trx_date = '06/03/2020'::date - '1 day'::interval
)
SELECT
    pt.product,
    prev.value AS yesterday,
    pt.value AS CURRENT_DATE,
    pt.value - prev.value AS delta
FROM
    product_table AS pt,
    prev
WHERE
    trx_date = '06/03/2020';

 product | yesterday | current_date | delta 
---------+-----------+--------------+-------
 apple   |       300 |          500 |   200



Related