I need to traspose a column into a row ( by concatenating it) with group by...
using : sql server 2019
Example
| Car_ID | Car_Name | Owner |
|---|---|---|
| 1 | Ferrari | Marco |
| 2 | Jeep | Enrico |
| 3 | Mercedes | Matteo |
| 1 | Ferrari | Andrea |
| 3 | Mercedes | Giorgio |
| 2 | Jeep | Gianluca |
How can i get this?
| Car_ID | Car_Name | Owners |
|---|---|---|
| 1 | Ferrari | Marco,Andrea |
| 2 | Jeep | Enrico,Gianluca |
| 3 | Mercedes | Matteo,Giorgio |
I tried something but i didn't get close enough to show something here.
Need to know your DB name to suggest appropriate answer. It's not pivot rather string aggregation. I will try to cover major RDBMs.
If you are using
sql serverorpostgresyou can usestring_agg()Query:
Output:
fiddle
If you are using
MySqlthen you can usegroup_concat():Query:
Output:
fiddle
If you are using
Oraclethen you can uselistagg()for this purpose:Query:
Output:
fiddle