Alison Ribeiro
Alison Ribeiro

Reputation: 69

Group cols in row in SQL PostgreSQL

Need group 3 col in 1 row

I have this table:

This query:

select cidade, grupo from dados;
|----------|--------|  
|Cidade    |Grupo   |  
|----------|--------|  
|varginha  |grande  |  
|----------|--------|  
|mimoso    |pequena |  
|----------|--------|  
|Sao Tumas |media   |  
|----------|--------|  

But, I need convert, or grouping cols in row in SQL, like this:

|---------|  
|Grouping |    
|---------|  
|varginha |  
|grande   |  
|---------|  
|mimoso   |     
|pequena  |  
|---------|  
|Sao Tumas|  
|media    |  
|---------|

Upvotes: 0

Views: 131

Answers (3)

Alison Ribeiro
Alison Ribeiro

Reputation: 69

Well... I Resolve this question using UNION ALL

Like this:

select cidade as col_data from dados union all select grupo as col_data from dados;

Upvotes: 0

hkoosha
hkoosha

Reputation: 1146

What you are trying to do is called concatenation in SQL realm. GROUP BY is completely a different beast (more info).

In your case, you want to put a new line in between: first column + new line + second column. In Postgres, using chr(10) you'll get the new line character, so:

postgres=# SELECT CONCAT("cidade", CHR(10), "grupo") AS "Grouping" FROM "dados";

 Grouping
----------
varginha
grande

mimoso
pequena

Sao Tumas
media
(3 rows)

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1270081

Are you just looking for concat():

select (cidade || ' ' || grupo) as grouping
from t;

You can put a new line as the separator. Usually, I don't recommend this unless you have a good reason.

Upvotes: 0

Related Questions