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_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.
1条答案
按热度按时间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
orpostgres
you can usestring_agg()
Query:
Output:
fiddle
If you are using
MySql
then you can usegroup_concat()
:Query:
Output:
fiddle
If you are using
Oracle
then you can uselistagg()
for this purpose:Query:
Output:
fiddle