SQL Server Comma separated values in a column in SQL

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

I am using Microsoft SQL server. I have a select statement that has number of columns queried from joining more than 4 tables, and the result table is shown as below,
| column1 | column2 | column3 | column4 |
| ------------ | ------------ | ------------ | ------------ |
| 1 | File1 | Table1 | Column1 |
| 1 | File1 | Table1 | Column2 |
| 1 | File1 | Table2 | Column1 |

Here, the values of Column4 are distinct that must be grouped and the result that I require is,

column1column2column3column4
1File1Table1Column1, Column2
1File2Table2Column1
91zkwejq

91zkwejq1#

you can use STRING_AGG

select column1,column2,column3,STRING_AGG(column4,',') as column4
from adds
group by column1,column2,column3

base Data

create table adds(
column1 varchar(100),   column2 varchar(100),   column3 varchar(100),   column4 varchar(100)
)
insert into adds values
(1, 'File1',    'Table1'    ,'Column1')
,(1,'File1',    'Table1'    ,'Column2')
,(1,'File1',    'Table2'    ,'Column1')

相关问题