SQL comma-separated row with Group By clause

You want to use FOR XML PATH construct: SELECT ACCOUNT, unit, SUM(state_fee), Stuff((SELECT ‘, ‘ + code FROM tblmta t2 WHERE t2.ACCOUNT = t1.ACCOUNT AND t2.unit = t1.unit AND t2.id = ‘123’ FOR XML PATH(”)), 1, 2, ”) [Codes] FROM tblmta t1 WHERE t1.id = ‘123’ GROUP BY ACCOUNT, unit See other examples here: SQL … Read more

SQL Query to get aggregated result in comma separators along with group by column in SQL Server

You want to use FOR XML PATH construct: select ID, stuff((select ‘, ‘ + Value from YourTable t2 where t1.ID = t2.ID for xml path(”)), 1,2,”) [Values] from YourTable t1 group by ID The STUFF function is to get rid of the leading ‘, ‘. You can also see another examples here: SQL same unit … Read more

Multiple rows to one comma-separated value in Sql Server [duplicate]

Test Data DECLARE @Table1 TABLE(ID INT, Value INT) INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400) Query SELECT ID ,STUFF((SELECT ‘, ‘ + CAST(Value AS VARCHAR(10)) [text()] FROM @Table1 WHERE ID = t.ID FOR XML PATH(”), TYPE) .value(‘.’,’NVARCHAR(MAX)’),1,2,’ ‘) List_Output FROM @Table1 t GROUP BY ID Result Set ╔════╦═════════════════════╗ ║ ID ║ List_Output ║ ╠════╬═════════════════════╣ ║ 1 ║ … Read more

How to make a query with group_concat in sql server [duplicate]

Query: SELECT m.maskid , m.maskname , m.schoolid , s.schoolname , maskdetail = STUFF(( SELECT ‘,’ + md.maskdetail FROM dbo.maskdetails md WHERE m.maskid = md.maskid FOR XML PATH(”), TYPE).value(‘.’, ‘NVARCHAR(MAX)’), 1, 1, ”) FROM dbo.tblmask m JOIN dbo.school s ON s.ID = m.schoolid ORDER BY m.maskname Additional information: String Aggregation in the World of SQL Server

How to use GROUP BY to concatenate strings in SQL Server?

No CURSOR, WHILE loop, or User-Defined Function needed. Just need to be creative with FOR XML and PATH. [Note: This solution only works on SQL 2005 and later. Original question didn’t specify the version in use.] CREATE TABLE #YourTable ([ID] INT, [Name] CHAR(1), [Value] INT) INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,’A’,4) INSERT INTO #YourTable ([ID],[Name],[Value]) … Read more