gpt4 book ai didi

SQL 按类型和位置唯一分组

转载 作者:行者123 更新时间:2023-11-29 13:33:47 24 4
gpt4 key购买 nike

给定这个数据集:

ID  type_id  Position
1 2 7
2 1 2
3 3 5
4 1 1
5 3 3
6 2 4
7 2 6
8 3 8

(只有 3 种不同的可能 type_id)我想返回一个数据集,每个 type_id 中的一个按位置排序。

所以它会像这样分组:

Results (ID): [4, 6, 5], [2, 7, 3], [null, 1, 8]

因此,第一组将由具有最高(相对)位置得分的每个条目 type_id 组成,第二组将具有第二高得分,第三组将仅由两个条目(和一个空条目)组成,因为有每个 type_id 不超过三个

这有意义吗?这可能吗?

最佳答案

类似的东西:

with CTE as (
select
row_number() over (partition by type_id order by Position) as row_num,
*
from test
)
select array_agg(ID order by type_id)
from CTE
group by row_num

SQL FIDDLE

of,如果你绝对需要数组中的空值:

with CTE as (
select
row_number() over (partition by type_id order by Position) as row_num,
*
from test
)
select array_agg(c.ID order by t.type_id)
from (select distinct row_num from CTE) as a
cross join (select distinct type_id from test) as t
left outer join CTE as c on c.row_num = a.row_num and c.type_id = t.type_id
group by a.row_num

SQL FIDDLE

关于SQL 按类型和位置唯一分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17975243/

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