2015-09-28 50 views
2

我有2条记录(说明用途)PostgreSQL的:加入2个阵列,最大值

| id  | access (int array) | 
| ---------------------------- | 
| 1  | {0,1,0}   | 
| 2  | {1,0,0}   | 

的表,我想选择这两个值,并把它们合并起来
获得最高值使得导致这种情况:

{1,1,0} 

访问数组可能增长到超过200个值和为此我想避免这样做的编程代码,(golang)。

基本上它和这个问题是一样的:Merge two (or more) arrays and keep values that are highest?但在我的情况下,分离的列与数组组合成一个字段。

UPDATES

  1. row(access)阵列总是具有的值的相同量
+1

是,'每行(访问)'具有相同数量的值的 – DonSeba

回答

1

尝试此查询(SqlFiddle):

select array_agg(elem) 
from (
    select distinct on (row_number) row_number, elem 
    from (
     select id, elem, row_number() over (partition by id) 
     from (
      select id, unnest(access) elem 
      from merge_test 
      where id in (1,2) 
      ) sub 
     ) sub 
    order by 1, 2 desc 
    ) sub; 

二进制阵列

如果阵列仅包含 '0' 和 '1',并且具有相同数目的值:

create table merge_binary_test (id int, access int[]); 
insert into merge_binary_test values 
(1, '{0,1,0,1}'), 
(2, '{1,0,0,1}'); 

select string_to_array(bit_or(elem)::text, null)::int[] 
from (
    select id, array_to_string(access, '')::varbit elem 
    from merge_binary_test 
    where id in (1,2) 
    ) sub 

string_to_array 
----------------- 
{1,1,0,1} 
(1 row) 
1

考虑以下为例:

create table arr(id int,access int[]); 
insert into arr values (1,'{0,1,0}'),(2,'{0,1,0}'),(3,'{0,0,9}'); 

所以该行将是:

id access 
-- ------- 
1 {0,1,0} 
2 {0,1,0} 
3 {0,0,9} 

现在一个函数可以来创建合并像下面阵列中的行:

CREATE 
    OR replace FUNCTION merge_array (
    arrval INT -- the total number of values in an array in my example its 3, but 200 is for yours 
    ,tbl TEXT --name of the table in which you want perform this function, 
    ,col TEXT -- name of the array col 
    ) 
RETURNS setof INTEGER [] AS $$ 

DECLARE qry TEXT; 

BEGIN 
    SELECT format('select translate(string_to_array(x.*::text,'','')::text,''()'','''')::int[] from (select %s from (select ' || col || ' ar from ' || tbl || ') as sq) as x ', egn) 
    INTO qry 
    FROM (
     SELECT string_agg('max(ar[' || val || '])', ',') egn 
     FROM (
      SELECT generate_series(1, arrval) val 
      ) t 
     ) tt; 

    RETURN QUERY 

    EXECUTE (qry); 
END;$$ 

LANGUAGE plpgsql 

用法:select merge_array(3,'arr','access') 结果:

merge_array 
----------- 
{0,1,9}