每组最高 [英] Highest per each group
本文介绍了每组最高的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
很难在这里显示我的实际表和数据,所以我将用示例表和数据来描述我的问题:
It's hard to show my actual table and data here so I'll describe my problem with a sample table and data:
create table foo(id int,x_part int,y_part int,out_id int,out_idx text);
insert into foo values (1,2,3,55,'BAK'),(2,3,4,77,'ZAK'),(3,4,8,55,'RGT'),(9,10,15,77,'UIT'),
(3,4,8,11,'UTL'),(3,4,8,65,'MAQ'),(3,4,8,77,'YTU');
表 foo
:
id x_part y_part out_id out_idx
-- ------ ------ ------ -------
3 4 8 11 UTL
3 4 8 55 RGT
1 2 3 55 BAK
3 4 8 65 MAQ
9 10 15 77 UIT
2 3 4 77 ZAK
3 4 8 77 YTU
我需要通过对每个 out_id
的最高 id
进行排序来选择所有字段。
预期输出:
I need to select all fields by sorting the highest id
of each out_id
.
Expected output:
id x_part y_part out_id out_idx
-- ------ ------ ------ -------
3 4 8 11 UTL
3 4 8 55 RGT
3 4 8 65 MAQ
9 10 15 77 UIT
使用PostgreSQL。
Using PostgreSQL.
推荐答案
Postgres特定(也是最快的)解决方案:
Postgres specific (and fastest) solution:
select distinct on (out_id) *
from foo
order by out_id, id desc;
使用窗口功能(第二快)
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;
请注意,两个解决方案都只会返回每个 id
一次,即使存在多个相同的 out_id
值也是如此。如果希望它们全部退回,请使用 dense_rank()
而不是 row_number()
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()
这篇关于每组最高的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文