Concatenate many rows into a single text string wi

2019-01-18 04:49发布

This question already has an answer here:

I have the following table: tblFile

tblFile

My Desired output:

enter image description here

I am Concatenating many rows into a single text string; however, I cannot get the grouping correct. As the code is now it will just display for each record in the FileNameString field: AAA,BBB,CCC,DDD,EEE,FFF

Any suggestions with the grouping!

SELECT FileID, Stuff(
(SELECT     N', ' + CONVERT(Varchar, FileName) 
FROM         tblFile  FOR XML PATH(''),TYPE )
.value('text()[1]','nvarchar(max)'),1,2,N'')AS FileNameString 
From tblFile
GROUP BY FileID

1条回答
男人必须洒脱
2楼-- · 2019-01-18 05:48

try this -

SELECT DISTINCT
      fileid
    , STUFF((
        SELECT N', ' + CAST([filename] AS VARCHAR(255))
        FROM tblFile f2
        WHERE f1.fileid = f2.fileid ---- string with grouping by fileid
        FOR XML PATH (''), TYPE), 1, 2, '') AS FileNameString
FROM tblFile f1
查看更多
登录 后发表回答