My table looks as follows:
| sensor | time | value |
|---|---|---|
| AAA | 2021-01-05 04:10:14 | 3.14159 |
| AAA | 2021-01-05 05:08:07 | 3.94756 |
| ABC | 2021-01-05 03:40:54 | 4.32543 |
I'm looking for a query that retrieves the rows corresponding to the last observation for each sensor, i.e.:
| sensor | time | value |
|---|---|---|
| AAA | 2021-01-05 05:08:07 | 3.94756 |
| ABC | 2021-01-05 03:40:54 | 4.32543 |
After doing some research I came across this solution:
SELECT DISTINCT ON (sensor) sensor, time, value
FROM observations
ORDER BY sensor, time DESC
The problem with the above is that it's rather costly for large tables.
A possible solution would be to have another table holding only the last observation for each sensor, separate from the one holding all the historical ones. While that would work, I was wondering if there is something more elegant, i.e. that allows me to keep a single table, while having a better performance.
Thanks in advance.