我有一张桌子
<button id="btn">btn</div>
<button id="btn2">Disable/Enable</div>
我想为每个用户选择User | Phone | Value
Peter | 0 | 1
Peter | 456 | 2
Peter | 456 | 3
Paul | 456 | 7
Paul | 789 | 10
值,而不是低于tresshold
对于tresshold 8,我希望结果是
MAX
我已经尝试了GROUP BY和HAVING,但我得到了
Peter | 456 | 3
Paul | 456 | 7
类似的查询逻辑在MySQL中有效,但我不太确定如何在PostgreSQL中使用GROUP BY。我不想打电话给GROUP BY。
答案 0 :(得分:3)
我得到了&#34; juergen d&#34;解决方案,我想出了这个,它给了我更快的结果
SELECT DISTINCT ON(user) user, phone, value
FROM table
WHERE value < 8
ORDER BY user, value DESC;
答案 1 :(得分:2)
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
答案 2 :(得分:1)
或者,您可以使用排名功能:
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