Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgresQL SQL: Converting results to array

The query below:

    SELECT  i_adgroup_id, i_category_id     FROM adgroupcategories_br     WHERE i_adgroup_id IN     (         SELECT i_adgroup_id         FROM adgroupusers_br         WHERE i_user_id = 103713     )     GROUP BY i_adgroup_id, i_category_id; 

Gives me results like this:

    i_adgroup_id integer | i_category_id smallint     ---------------------|-----------------------     15938                | 2     15938                | 3     15938                | 4     15942                | 1     15942                | 2 

What I want is results like this:

    i_adgroup_id integer | i_category_id smallint[]     ---------------------|-----------------------     15938                | { 2, 3, 4 }     15942                | { 1, 2 } 

How can I change the original SQL query to give me the result above?

like image 253
DotNetDateQuestion Avatar asked Apr 19 '11 23:04

DotNetDateQuestion


People also ask

How do I declare a string array in PostgreSQL?

Syntax. In the above syntax, we can declare a String Array data type at the time of table creation. Where table name is the specified table name that we need to create and column 1, column 2, and column n declared with the data type of array and it separated by using a comma.

How do you create an array in SQL?

Define arrays as SQL variables. Use the ARRAY_AGG built-in function in a cursor declaration, to assign the rows of a single-column result table to elements of an array. Use the cursor to retrieve the array into an SQL out parameter. Use an array constructor to initialize an array.

What is text [] in PostgreSQL?

PostgreSQL supports a character data type called TEXT. This data type is used to store character of unlimited length. It is represented as text in PostgreSQL. The performance of the varchar (without n) and text are the same.

How do I declare an array variable in PostgreSQL?

PostgreSQL Array type PL/pgSQL in PostgreSQL allows us to declare a variable as an ARRAY type. This ARRAY can be either a base or a custom type. For example, if we want to store a list of PINCODE values, then, we can declare the variable as v_pincode INT[].


1 Answers

You want to use array_agg, this should work:

SELECT i_adgroup_id, array_agg(i_category_id) FROM adgroupcategories_br WHERE i_adgroup_id IN (     SELECT i_adgroup_id     FROM adgroupusers_br     WHERE i_user_id = 103713 ) GROUP BY i_adgroup_id; 

Note that i_category_id is no longer in the GROUP BY as it is now being aggregated.

like image 145
mu is too short Avatar answered Sep 20 '22 19:09

mu is too short