I have a simple order table in my postgres db and I want to join from a table of payments to create a new column for each order where the latest payment is indicated.
Each payment row looks like this:
id: 1, order_id: 1, status: paid, date: 2024-04-08 16:34:09.860634+02
And if there are more payments to the same order, how can I assign the latest payment (based on date, or id, or simply the latest in the sequence) to the given order row? Some orders might be refunded, therefore I want to take the latest record that has refunded status and append it to the order.
2
Answers
After adjusting the query which I had linked to in the comments, I came up with the following. I have used DB Fiddle to provide a testing ground.
Table
orders
– columns and naming conventions are just for testing, you would use your normal table schema and your usual way of naming columns.Table
payments
– like above.The query below extracts the latest payment, since you mentioned:
Other ways could be used – you would just target that particular column, instead of the date (which I’m doing in the query).
Output
Schema (PostgreSQL v10)
View on DB Fiddle
You can use
DISTINCT ON
. For example:Result:
See running example at db<>fiddle.