Postgresql 使用条件获取最大值

Postgresql 使用条件获取最大值,postgresql,case-when,Postgresql,Case When,如何获得每个id的最大状态? 请注意,如果状态为成功,则必须忽略以后的状态 以下是示例数据: +-------+------------+---------------------+ | id | status | created_at | +-------+------------+---------------------+ | 76efg | expired | 2021-01-07 05:19:03 | | 76efg | pending |

如何获得每个id的最大状态? 请注意,如果状态为成功,则必须忽略以后的状态

以下是示例数据:

+-------+------------+---------------------+
|  id   |   status   |     created_at      |
+-------+------------+---------------------+
| 76efg | expired    | 2021-01-07 05:19:03 |
| 76efg | pending    | 2021-01-14 06:55:13 |
| fsf56 | successful | 2021-01-25 11:18:03 |
| ghl56 | successful | 2021-01-08 05:19:03 |
| ghl56 | expired    | 2021-02-02 17:37:10 |
+-------+------------+---------------------+
期望输出:

+-------+------------+---------------------+
|  id   |   status   |     created_at      |
+-------+------------+---------------------+
| 76efg | pending    | 2021-01-14 06:55:13 |
| fsf56 | successful | 2021-01-25 11:18:03 |
| ghl56 | successful | 2021-01-08 05:19:03 |
+-------+------------+---------------------+

以下是一种使用分析函数的方法:

以cte为例 选择*,计数*过滤器,其中状态='successful'超过按id cnt划分的分区, 分区上的行数按id顺序按DESC rn创建 从你的桌子上 选择id、状态、已创建位置 来自cte t1 哪里 rn=1和cnt=0或 cnt>0且状态为“成功”且不存在从cte t2中选择1 其中t2.id=t1.id,且 t2.创建时间>t1.创建时间和 t2.状态=‘成功’; 外部查询中的过滤逻辑在两种情况下保留记录:

给定id组的任何记录都没有成功状态,在这种情况下,我们采用最新记录,或者 给定id组存在成功记录,在这种情况下,我们采用最新的成功记录。
你说的max是指按字母顺序排在最后的?