首页 > 解决方案 > 如何找出每个 integration_id 组的 name 列被批准的最低日期?

问题描述

id | integration_id | date | name
(1, 1, 2021-04-14 18:04:18.167+05:30, approved)
(2, 1, 2021-04-15 18:04:18.167+05:30, approved)
(3, 2, 2021-04-16 18:04:18.167+05:30, not approved)
(4, 2, 2021-04-17 18:04:18.167+05:30, approved)

如果有多个这样的 integration_id,我们只需要选择已批准的行,我如何编写查询以从 postgresql 中的每个集成 id 组中获取最小日期行。

id | integration_id | date | name
(1, 1, 2021-04-14 18:04:18.167+05:30, approved)
(4, 2, 2021-04-17 18:04:18.167+05:30, approved)

这应该是我的最终答案。

标签: postgresql

解决方案


在 Postgres 上,DISTINCT ON在这里派上用场:

SELECT DISTINCT ON (integration_id) *
FROM yourTable
WHERE name = 'approved'
ORDER BY integration_id, date;

推荐阅读