Henrique Rigitano
Henrique Rigitano

Reputation: 37

Rearrange information in several lines to just one

I've got a table that was created in a way that any person with more than one car end up appearing in more than one line:

mytable:

 name       car
 -----      -----
 Joe        Ford    
 Alex       Ferrari        
 Alex       Audi    
 Jimmy      Fiat

Is there any way to create a SQL query that returns that table rearranged to only one person per line, and concatenated cars?

wanted table:

 name       car
 -----      -----
 Joe        Ford        
 Alex       FerrariAudi                  
 Jimmy      Fiat

Upvotes: 0

Views: 37

Answers (1)

Steffen Bobek
Steffen Bobek

Reputation: 642

Use GROUP BY. Concatenation of car types depends on the database you use. In Postgres you could write

SELECT name, string_agg(car, '') AS car FROM mytable GROUP BY name

Upvotes: 1

Related Questions