【问题标题】:PostgreSQL: Returning the most recent rows grouping by a foreign key columnPostgreSQL:返回按外键列分组的最新行
【发布时间】: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


【解决方案1】:

你可以试试这个。 使用ROW_NUMBER和窗口函数在子查询中按person_id分割行号并按date_time排序,然后得到行号为1

CREATE TABLE credit(
   id int,
   person_id int,
   transaction float,
   "total credit" float,
   date_time timestamp
);

INSERT INTO credit values (345,1 ,-1.00,34.50, '2018-08-29 12:00:00.000');
INSERT INTO credit values (897,1 ,5.45 ,39.95, '2018-08-29 12:34:00.000');
INSERT INTO credit values (378,2 ,0.01 ,0.01 , '2018-08-29 08:00:00.000');
INSERT INTO credit values (789,2 ,20.00,20.01, '2018-08-29 09:00:00.000');

查询 1

SELECT * FROM (
    SELECT *,ROW_NUMBER() OVER (PARTITION BY person_id  ORDER BY date_time DESC) rn
    FROM credit
) t1
where rn = 1

Results

|  id | person_id | transaction | total credit |            date_time | rn |
|-----|-----------|-------------|--------------|----------------------|----|
| 897 |         1 |        5.45 |        39.95 | 2018-08-29T12:34:00Z |  1 |
| 789 |         2 |          20 |        20.01 | 2018-08-29T09:00:00Z |  1 |

【讨论】:

  • 非常感谢您提供的详细示例!
  • @ty2k 没问题,很高兴为您提供帮助
【解决方案2】:

使用distinct on:

select distinct on (person_id) t.*
from t
order by person_id, date_time desc

【讨论】:

    猜你喜欢
    • 2021-12-24
    • 1970-01-01
    • 2023-03-13
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    相关资源
    最近更新 更多