繁体   English   中英

如何在postgresql9.4中根据第一个索引获取数组元素的第二个索引值?

[英]How to get second index values of array elements according first index in postgresql9.4?

我有一个名为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]]);

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

首先,我要选择6个数组元素,这些数组元素的第一个索引值小于67,看起来像这样:

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

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

12, 15, 47, 27, 97, 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM