1

给定这个数据集:

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

这有意义吗?这可能吗?

4

1 回答 1

1

类似的东西:

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 小提琴

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

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 小提琴

于 2013-07-31T18:05:25.227 回答