0

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    |  
|---------|
3
  • In your resultset, does each block (like varginha grande) represents a single record, or two different records? Commented Nov 9, 2019 at 16:27
  • each line is single record. like: line 1 - varginha, grande / line 2 - mimoso pequena / line 3 - sao tumas, media Commented Nov 9, 2019 at 17:17
  • OK. So what is wrong with the answer by Gordon Linoff? It seems to return the proper results for your sample data. Commented Nov 9, 2019 at 17:21

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

I need the convert results of 2 cols in 2 rows. concat not work for me.
@AlisonRibeiro . . . Your data has 2 columns and 3 rows. The result set looks like it has 3 rows, so your comment does not make sense.
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.