sql - How to aggragate integers in postgresql? -
i have query gives list of ids:
id 2 3 4 5 6 25 id integer.
i want result in array of integers type:
id 2,3,4,5,6,25 i wrote query:
select string_agg(id::text,',') ..... i have convert text otherwise won't work. string_agg expect (text,text)
this works fine thing result should later used in many places expect array of integers.
i tried :
select ('{' || string_agg(id::text,',') || '}')::integer[] ... which gives: {2,3,4,5,6,25} in type int4 integer[] isn't correct type... need same type array.
for example select array[4,5] gives array integer[]
in simple words want result of query work (for example):
select * b b.id = (first query result) // aka: = (array[2,3,4,5,6,25]) this failing expect array , doesn't work regular integer[], error:
error: operator not exist: integer = integer[]
note: result of query part of function , saved in variable later work. please don't take places bypass problem , offer solution won't give array of integers.
edit: why
select * b b.id = (array [4,5]) is working. but
select * b b.id = any(select array_agg(id) ..... ) doesn't work
select * b b.id = any(select array_agg(4)) doesn't work either
the error still:
error: operator not exist: integer = integer[]
expression select array_agg(4) returns set of rows (actually set of rows 1 row). hence query
select * b b.id = (select array_agg(4)) -- error tries compare integer (b.id) value of row (which has 1 column of type integer[]). raises error.
to fix should use subquery returns integers (not arrays of integers):
select * b b.id = (select unnest(array_agg(4))) alternatively, can place column name of result of select array_agg(4) argument of any, e.g.:
select * b cross join (select array_agg(4)) agg(arr) b.id = (arr) or
with agg ( select array_agg(4) arr) select * b cross join agg b.id = (arr) more formally, first 2 queries use any of form:
expression operator (subquery) and other 2 use
expression operator (array expression) like described in documentation: 9.22.4. any/some , 9.23.3. any/some (array).
Comments
Post a Comment