2016-02-01 187 views
0

我已經表稱爲arraytable - >create table arraytable(id int, somearray int[][])如何根據postgresql9.4中的第一個索引獲取數組元素的第二個索引值?

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. 

回答

0

這是這麼難看我敢肯定有一個更好的方式來做到這一點,但因爲沒有人回答了這個問題,我會後這個答案銘記,我不認爲這是一個很好的解決方案,一個穩定的。不要在生產中使用它!對我來說,這僅僅是一個練習,關於多維數組如何在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應該出現在輸出中。

+0

希望有人提供一個更好的答案來學習,因爲我幾乎沒有任何多維數組的經驗:-) –

相關問題