gpt4 book ai didi

sql - 每组最高

转载 作者:行者123 更新时间:2023-11-29 11:32:49 25 4
gpt4 key购买 nike

很难在此处显示我的实际表格和数据,因此我将使用示例表格和数据来描述我的问题:

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 进行排序来选择所有字段。
预期输出:

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。

最佳答案

Postgres 特定(且最快)的解决方案:

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

使用 window function 的标准 SQL 解决方案(第二快)

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;

请注意,即使有多个相同的 out_id 值,这两种解决方案都只会返回每个 id 一次。如果您希望它们全部返回,请使用 dense_rank() 而不是 row_number()

关于sql - 每组最高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28125273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com