Re: Converting row elements into a arrays?

From: Rob Sargent <robjsargent(at)gmail(dot)com>
To: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Converting row elements into a arrays?
Date: 2023-03-02 22:10:24
Message-ID: 660edb74-9a49-8d68-c489-7de99d955c60@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 3/2/23 14:49, Ron wrote:
> On 3/2/23 15:45, Rob Sargent wrote:
>> On 3/2/23 13:58, Ron wrote:
>>> Postgresql 12.13
>>>
>>> Given the sample below, I'm looking for how to generate this
>>> output.  It's like GROUP BY, but generating an array instead of an
>>> aggreate number.
>>>  f1 | f2_array
>>> ----+---------
>>> 1 | {1,2,3}
>>>   2 | {1,2,3,4}
>>>   3 | {1,2}
>>>
>>> The ultimate goal is to somehow use pg_index.indkey to get column
>>> names from pg_attribute.
>>>
>>> create table foo (f1 int, f2 int);
>>> insert into foo values (1, 1);
>>> insert into foo values (1, 2);
>>>
> [snip]
>>
>> In which environment are you accessing that array?  psql only?
>
> Correct.
>

For multiple columns it's a litte messier ( if you have different data
types in your columns)

create table foo (f1 int, f2 int, f3 text);
insert into foo values (1, 1,'asdf');
insert into foo values (1, 2, 'qerr');

select f1, array_agg(array[f2::text,f3]) from foo group by f1;
 f1 |      array_agg
----+---------------------
  1 | {{1,asdf},{2,qerr}}
(1 row)

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Thorsten Glaser 2023-03-02 23:02:06 Re: DISTINCT *and* ORDER BY in aggregate functions on expressions(!)y
Previous Message Ron 2023-03-02 21:57:55 Re: Converting row elements into a arrays?