PostgreSQL - 每个用户的最大值

PostgreSQL - MAX value for every user

我有一个table

User | Phone | Value
Peter | 0 | 1
Peter | 456 | 2
Peter | 456 | 3
Paul | 456 | 7 
Paul | 789 | 10

我想select给每个用户MAX值,比它还低一个tresshold

对于 tresshold 8,我希望结果是

Peter | 456 | 3
Paul | 456 | 7

我已经尝试使用 HAVING 进行 GROUP BY,但我得到

column "phone" must appear in the GROUP BY clause or be used in an aggregate function

类似的查询逻辑在 MySQL 中有效,但我不太确定如何在 PostgreSQL 中使用 GROUP BY 进行操作。我不想 GROUP BY phone.

select t1.*
from your_table t1
join
(
    select user, max(value) as max_value
    from your_table
    where value < 8
    group by user
) t2 on t1.user = t2.user and t1.value = t2.max_value

或者,您可以使用排名函数:

select * from 
(
select *, RANK() OVER (partition by [user] ORDER BY t.value desc ) as value_rank from test_table as t
where t.value < 8
) as t1
where value_rank = 1

在我得到 "juergen d" 解决方案的结果后,我想到了这个可以更快地得到相同结果的方法

SELECT DISTINCT ON(user) user, phone, value
FROM table
WHERE value < 8
ORDER BY user, value DESC;