Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do I get:

id       Name       Value 1          A          4 1          B          8 2          C          9 

to

id          Column 1          A:4, B:8 2          C:9 
like image 890
Eldila Avatar asked Nov 07 '08 19:11

Eldila


People also ask

How do I group concatenate strings in SQL?

MySQL | Group_CONCAT() Function. The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.

Can I use Concat with GROUP BY?

To concatenate strings in MySQL with GROUP BY, you need to use GROUP_CONCAT() with a SEPARATOR parameter which may be comma(') or space (' ') etc.

How do I concatenate text from multiple rows into a single text string in SQL Server?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.

Can I use GROUP BY and where together in SQL?

Absolutely. It will result in filtering the records on your date range and then grouping it by each day where there is data.


1 Answers

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]) VALUES (1,'B',8) INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)  SELECT    [ID],   STUFF((     SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX))      FROM #YourTable      WHERE (ID = Results.ID)      FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')   ,1,2,'') AS NameValues FROM #YourTable Results GROUP BY ID  DROP TABLE #YourTable 
like image 125
Kevin Fairchild Avatar answered Oct 14 '22 14:10

Kevin Fairchild