Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

99
Views
postgresql Get latest value before date

Let's say I have the following Inventory table.

id  item_id  stock_amount           Date
(1,   1,        10,         '2020-01-01T00:00:00')
(2,   1,         9,         '2020-01-02T00:00:00')
(3,   1,         8,         '2020-01-02T10:00:00')
(4,   3,        11,         '2020-01-03T00:00:00')
(5,   3,        13,         '2020-01-04T00:00:00')
(6,   4,         7,         '2020-01-05T00:00:00')
(7,   2,        12,         '2020-01-06T00:00:00')

Basically, per each day, I want to get the sum of stock_amount for each unique item_id but it should exclude the current day's stock amount. The item_id chosen should be the latest one. This is to calculate the starting stock on each day. So the response in this case would be:

       Date            starting_amount
'2020-01-01T00:00:00'         0
'2020-01-02T00:00:00'         10
'2020-01-03T00:00:00'         8 
'2020-01-04T00:00:00'         19 -- # -> 11 + 8 (id 5 + id 3)
'2020-01-05T00:00:00'         21 -- # -> 13 + 8
'2020-01-06T00:00:00'         28 -- # -> 7 + 13 + 8

Any help would be greatly appreciated.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Using nested subqueries like this:

select
  Date,
  coalesce(sum(stock_amount), 0) starting_amount
from
(
  select
    row_number() over(partition by i1.Date, item_id order by i2.Date desc) i,
    i1.Date,
    i2.item_id,
    i2.stock_amount
  from
    (select distinct date_trunc('day', Date) as Date from Inventory) i1
    left outer join
    Inventory i2
    on i2.Date < i1.Date
) s
where i = 1
group by Date
order by Date

This query sorts in descending order and uses the first row.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!