【发布时间】:2019-02-04 19:07:00
【问题描述】:
我有一张类似这样的表格:
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 |
+---------+----------------+-------------+--------------+-------------------------+
如何在 Postgres 中编写查询以仅返回按表中每个唯一 person_id 分组的最新(按 date_time DESC)行,像这样?
+---------+----------------+-------------+--------------+-------------------------+
| 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 |
+---------+----------------+-------------+--------------+-------------------------+
【问题讨论】:
标签: sql postgresql greatest-n-per-group