Postgres GROUP BY在包含主键时返回所有行

时间:2017-09-27 16:06:43

标签: postgresql aggregate-functions

我有一个简单的group by语句,我需要检索具有为聚合计划的最大值的行的主键id

select id, max(scheduled) from event group by customer_id, id;

这将返回所有结果,其中计划值为每个客户的最大(计划)。

如果我没有包含ID,则聚合按预期工作。

select max(scheduled) from event group by customer_id;

2 个答案:

答案 0 :(得分:2)

设计PK是独一无二的。因此,您可以获得与PK值一样多的组。 你可以使用:

SELECT id, customer_id, scheduled AS max_scheduled
FROM event
WHERE (customer_id, scheduled) = (select customer_id, max(scheduled) 
                                  from event 
                                  group by customer_id);

答案 1 :(得分:1)

实现目标的另一种方法是使用DISTINCT ON

SELECT DISTINCT ON (customer_id) id, scheduled
FROM event
ORDER BY customer_id, scheduled DESC;