SQL Server SQL - Pivot Column To Rows with Group By and Concat [duplicate]

wnavrhmk  于 2023-05-16  发布在  其他
关注(0)|答案(1)|浏览(175)

This question already has answers here:

How to concatenate text from multiple rows into a single text string in SQL Server (47 answers)
Simulating group_concat MySQL function in Microsoft SQL Server 2005? (12 answers)

Closed 2 days ago.

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_IDCar_NameOwners
1FerrariMarco,Andrea
2JeepEnrico,Gianluca
3MercedesMatteo,Giorgio

I tried something but i didn't get close enough to show something here.

kzipqqlq

kzipqqlq1#

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 server or postgres you can use string_agg()

Query:

select Car_ID,Car_Name,string_agg(Owner,',') as Owners from Cars
group by Car_ID,Car_Name

Output:

Car_IDCar_NameOwners
1FerrariMarco,Andrea
2JeepEnrico,Gianluca
3MercedesMatteo,Giorgio

fiddle

If you are using MySql then you can use group_concat() :

Query:

select Car_ID,Car_Name,group_concat(Owner) as Owners from Cars
group by Car_ID,Car_Name

Output:

Car_IDCar_NameOwners
1FerrariMarco,Andrea
2JeepEnrico,Gianluca
3MercedesMatteo,Giorgio

fiddle

If you are using Oracle then you can use listagg() for this purpose:

Query:

select Car_ID,Car_Name,listagg(Owner,',') as Owners from Cars
group by Car_ID,Car_Name

Output:

CAR_IDCAR_NAMEOWNERS
3MercedesMatteo,Giorgio
1FerrariMarco,Andrea
2JeepEnrico,Gianluca

fiddle

相关问题