I have a sql table which is being updated hourly through API. Sample is:
id | time | firstname | lastname | salary | location | country |
---|---|---|---|---|---|---|
1 | 2023-03-08 07:47:58 | John | 10000 | |||
1 | 2023-03-08 07:50:58 | Lenny | Phoenix | USA | ||
1 | 2023-03-08 07:55:58 | 5000 |
What i am looking in target is only 1 row that should contain all latest updated value, so the sample will look somewhat like this:
id | time | firstname | lastname | salary | location | country |
---|---|---|---|---|---|---|
1 | 2023-03-08 07:55:58 | John | Lenny | 5000 | Phoenix | USA |
Is there any way this can be achieved through Postgres query?
Please suggest.
Thanks in advance
2
Answers
Using array_agg can do the trick :
array_agg
withorder
andfilter
to group data into an array (only not empty data).In where
filter
, if you havenull
values then usewhere column is not null
instead.to_json
to transform the array into json then using->-1
we get the latest elementDemo here
Small example using array_agg, an order by and a filter: