Concatenate columns in a single Postgresql row

1

I have a situation that would make it much easier .. if I could return the data of a specific column in a single line:

For example:

Table A:

Codigo | Descricao
-------------------
1      | Descricao 1
2      | Descricao 2
3      | Descricao 3

I would like to build an sql that would return me on a single line like this:

1,2,3

Only the code column ..

Does anyone have any idea how it is possible to do this .. and if it is possible?

    
asked by anonymous 23.06.2017 / 16:57

2 answers

3

Use the array_agg(expression) function:

Select array_agg(codigo) from tabela A

In the link you can see PostgreSQL documentation for more information.

    
23.06.2017 / 17:03
2

Structure:

CREATE TABLE public.foobar
(
    Codigo BIGINT,
    Descricao TEXT
);

Data:

INSERT INTO public.foobar( Codigo, Descricao ) VALUES ( 1, 'Descricao 1' );
INSERT INTO public.foobar( Codigo, Descricao ) VALUES ( 2, 'Descricao 2' );
INSERT INTO public.foobar( Codigo, Descricao ) VALUES ( 3, 'Descricao 3' );

Inquiry:

SELECT string_agg( Codigo::text, ',' ) FROM public.foobar;

Output:

1,2,3
    
23.06.2017 / 20:35