【问题标题】:How to get second index values of array elements according first index in postgresql9.4?如何根据 postgresql 9.4 中的第一个索引获取数组元素的第二个索引值?
【发布时间】:2016-02-01 13:05:09
【问题描述】:

我有一个名为 arraytable 的表 -> create table arraytable(id int, somearray int[][])

INSERT INTO arraytable(id, somearray) values(1,array[[3,5],[4,12]]);
INSERT INTO arraytable(id, somearray) values(2,array[[7,15],[13,47],[15,27],[18,97]]);
INSERT INTO arraytable(id, somearray) values(3,array[[56,1],[67,78],[105,78]]);

我不知道如何根据数组元素的特定第一索引值选择所有行中数组元素的第二索引值;

首先,我想选择第一个索引值小于 67 的 6 个数组元素,如下所示:

[4,12],[7,15],[13,47],[15,27],[18,97],[56,1] 

现在我需要选择第二个索引值,如下所示:

12, 15, 47, 27, 97, 1.

【问题讨论】:

    标签: arrays database postgresql-9.4


    【解决方案1】:

    这太丑了,我确信有更好的方法可以做到这一点,但由于没有人回答这个问题,我会发布这个答案,记住我认为这不是一个好的解决方案和一个稳定的解决方案.不要在生产中使用它!这对我来说只是一个练习,我对多维数组如何在 Postgres 中工作的知识非常有限。

    只是为了回答:

    with x as (
      select foo.id, goo.nr, goo.first_ind, foo.somearray 
      from (
        select *, somearray[1:array_upper(somearray,1)][1] AS first_indexes 
        from arraytable
      ) foo, 
      unnest(foo.first_indexes) WITH ORDINALITY goo(first_ind,nr) 
      where goo.first_ind < 67
    ) 
    select string_agg(z.second_ind::text, ', ' order by x.id, x.nr) 
    from x 
    join (
      select * 
      from (
        select id, first_ind, somearray[1:array_upper(somearray,1)][2:3] AS second_indexes 
        -- [2:3] should actually be [2] but for some reason it wouldn't work? so this is specific to data with 2 indexes
        from x
      ) y, 
      unnest(y.second_indexes) WITH ORDINALITY goo(second_ind,nr)
    ) z on 
      x.id=z.id 
      and x.nr=z.nr 
      and x.first_ind=z.first_ind;
    

    输出:

         string_agg
    --------------------
    5, 12, 15, 47, 27, 97, 1
    (1 row)
    

    另外,{3,5} 应该被考虑在内,所以5 应该出现在输出中。

    【讨论】:

    • 希望有人能提供更好的答案来学习,因为我对多维数组几乎没有任何经验:-)
    猜你喜欢
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 2020-11-27
    • 2023-01-17
    • 2018-06-06
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多