Group values from different columns into one, separated by commas

1

I have the following select :

SELECT DISTINCT ORGAO, UNIDADE FROM TESTE

Where the following result is generated:

Órgao Unidade
1     2
1     3
1     4
1     5

4 records of the same organ are returned, but with different units. What I wanted was to return only one row with 2 columns, the first organ (1) and the second Unit (2,3,4,5) separated by commas.

How can I do this? Thanks in advance.

    
asked by anonymous 01.09.2016 / 23:13

1 answer

0

What you are trying to do does not seem to be a good idea, and usually when you go down this path, it is a sign that there is something wrong in your understanding of the purpose of the query or the result generated.

However, assuming that's exactly what you want. You could use LISTAGG of oracle in this way:

SELECT DISTINCT
    orgao,
    LISTAGG(unidade, ',') WITHIN GROUP (ORDER BY unidade) AS unidades
FROM TESTE
GROUP BY orgao;

Source: link

    
01.09.2016 / 23:24