Note that there are some explanatory texts on larger screens.

plurals
  1. POReturn multiple values and populate column in array like manner
    primarykey
    data
    text
    <p>I am using Postgres 9.3 on MacOSX. </p> <p>I am wondering how I can return multiple values (depending on certain criterion) and use them to populate a column in a list/array like manner? </p> <pre><code>--DUMMY DATA CREATE TABLE tbl ( id VARCHAR(2) PRIMARY KEY ,name TEXT ,year_born NUMERIC ,nationality TEXT ); INSERT INTO tbl(id, name, year_born, nationality) VALUES ('A1','Bill',2001,'American') ,('B1','Anna',1997,'Swedish') ,('A2','Bill',1991,'American') ,('B2','Anna',2004,'Swedish') ,('B3','Anna',1989,'Swedish') ,('A3','Bill',1995,'American'); SELECT * FROM tbl; id | name | year_born | nationality ---+------+-----------+------------ A1 | Bill | 2001 | American B1 | Anna | 1997 | Swedish A2 | Bill | 1991 | American B2 | Anna | 2004 | Swedish B3 | Anna | 1989 | Swedish A3 | Bill | 1995 | American </code></pre> <p>I pool over column <code>name, nationality</code> by using <code>SELECT DISTINCT ON</code> clause as in the below code</p> <pre><code>CREATE TABLE another_tbl ( name TEXT, nationality TEXT, ids VARCHAR ); CREATE FUNCTION f1() RETURNS SETOF another_tbl AS $$ SELECT DISTINCT ON (name, nationality) name, nationality, id FROM tbl GROUP BY name, nationality, ID; $$ LANGUAGE sql SELECT * FROM f1(); name | nationality | ids ------+-------------+----- Anna | Swedish | B1 Bill | American | A1 </code></pre> <p>So, here is the thing which I do not know how to achieve, but which I reckon is fairly easy. I want column <code>ids</code> to be populated by all the id's corresponding to the names in the <code>name</code> column as seen below.</p> <p>Desired output:</p> <pre><code> SELECT * FROM f1(); name | nationality | ids ------+-------------+----- Anna | Swedish | B1, B2, B3 Bill | American | A1, A2, A3 </code></pre> <p><strong>Update</strong></p> <p>Found out about <code>ARRAY</code> which I use together with class <code>VARCHAR</code> for column <code>ids</code> in <code>another_tbl</code>. However, I get a mismatch call saying <code>Final statement returns character varying instead of</code>character varying[]<code>at column 3</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload