Home > OS >  PostgreSQL - Minus current day to previous day
PostgreSQL - Minus current day to previous day

Time:06-08

My SQL query

SELECT date_time, country, volume FROM my_table GROUP BY country, date_time ORDER BY date_time DESC

Is it possible?

enter image description here

CodePudding user response:

With the Window Function LAG() you can access the previous record of a partition:

SELECT date_time, country, volume,
  volume - LAG(volume) OVER (PARTITION BY country ORDER BY date_time
                             ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)
FROM my_table 
ORDER BY date_time DESC

Demo: db<>fiddle

  • Related