Concatenate many rows into a single text string with grouping [duplicate]

给你一囗甜甜゛ 提交于 2019-11-27 01:59:38

问题


I have the following table: tblFile

My Desired output:

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:


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


来源:https://stackoverflow.com/questions/18362653/concatenate-many-rows-into-a-single-text-string-with-grouping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!