Highest per each group

眉间皱痕 提交于 2019-12-05 17:50:26

Postgres specific (and fastest) solution:

select distinct on (out_id) *
from foo
order by out_id, id desc;

Standard SQL solution using a window function (second fastest)

select id, x_part, y_part, out_id, out_idx
from (
  select id, x_part, y_part, out_id, out_idx, 
         row_number() over (partition by out_id order by id desc) as rn
  from foo
) t
where rn = 1
order by id;

Note that both solutions will only return each id once, even if there are multiple out_id values that are the same. If you want them all returned, use dense_rank() instead of row_number()

select * 
from foo 
where (id,out_id) in (
select max(id),out_id from foo group by out_id
) order by out_id

Finding max(val) := finding the record for which no larger val exists:

SELECT * 
FROM foo f
WHERE NOT EXISTS (
   SELECT 317
   FROM foo nx
   WHERE nx.out_id = f.out_id
   AND nx.id > f.id
   );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!