I have a table that looks similar to this:
credit
+---------+----------------+-------------+--------------+-------------------------+
| id (PK) | person_id (FK) | transaction | total credit | date_time |
+---------+----------------+-------------+--------------+-------------------------+
| 345 | 1 | -1.00 | 34.50 | 2018-08-29 12:00:00.000 |
| 897 | 1 | 5.45 | 39.95 | 2018-08-29 12:34:00.000 |
| 378 | 2 | 0.01 | 0.01 | 2018-08-29 08:00:00.000 |
| 789 | 2 | 20.00 | 20.01 | 2018-08-29 09:00:00.000 |
+---------+----------------+-------------+--------------+-------------------------+
How would I write a query in Postgres to return only the most recent (by date_time DESC
) row grouped by each unique person_id
in the table, like this?
+---------+----------------+-------------+--------------+-------------------------+
| id (PK) | person_id (FK) | transaction | total credit | date_time |
+---------+----------------+-------------+--------------+-------------------------+
| 897 | 1 | 5.45 | 39.95 | 2018-08-29 12:34:00.000 |
| 789 | 2 | 20.00 | 20.01 | 2018-08-29 09:00:00.000 |
+---------+----------------+-------------+--------------+-------------------------+