I am using Postgres 9.3 on MacOSX.
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?
--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
I pool over column name, nationality
by using SELECT DISTINCT ON
clause as in the below 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
So, here is the thing which I do not know how to achieve, but which I reckon is fairly easy. I want column ids
to be populated by all the id's corresponding to the names in the name
column as seen below.
Desired output:
SELECT * FROM f1();
name | nationality | ids
------+-------------+-----
Anna | Swedish | B1, B2, B3
Bill | American | A1, A2, A3
Update
Found out about ARRAY
which I use together with class VARCHAR
for column ids
in another_tbl
. However, I get a mismatch call saying Final statement returns character varying instead of
character varying[]at column 3
.