Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate all strings from a certain column for each group

Tags:

Suppose I have this table [Table1]

Name    Mark ------- ------ ABC     10 DEF     10 GHI     10 JKL     20 MNO     20 PQR     30 

What should be my SQL statement to retrieve a record that looks like this: (group by [mark]). I have done the 1 and 2 columns but don't know how to accomplish the third column (concat the [name] with the same [mark])

mark count     names ---- -----     ----------- 10       3     ABC,DEF,GHI 20       2     JKL,MNO 30       1     PQR 

I'm using Microsoft SQL. Please help. Thanks

like image 503
yonan2236 Avatar asked Jul 05 '11 07:07

yonan2236


People also ask

How do you concatenate rows by grouping data by column?

In the Advanced Combine Rows window, choose the column which you want to combine rows based on, and click Primary Key to set it as key column. 3. Select the column you need to combine, click Combine, and choose one delimiter you use to separate the combined contents.

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 a list of items in a string?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.


2 Answers

If MS SQL 2005 or higher.

declare @t table([name] varchar(max), mark int)  insert @t values ('ABC', 10), ('DEF', 10), ('GHI', 10),     ('JKL', 20), ('MNO', 20), ('PQR', 30)   select t.mark, COUNT(*) [count]     ,STUFF((         select ',' + [name]         from @t t1         where t1.mark = t.mark         for xml path(''), type     ).value('.', 'varchar(max)'), 1, 1, '') [values] from @t t group by t.mark 

Output:

mark        count       values ----------- ----------- -------------- 10          3           ABC,DEF,GHI 20          2           JKL,MNO 30          1           PQR 
like image 98
Kirill Polishchuk Avatar answered Sep 21 '22 23:09

Kirill Polishchuk


Here's a performance-related answer!

http://jerrytech.blogspot.com/2010/04/tsql-concatenate-strings-1-2-3-and.html

Using XML functions in a large query is a performance killer.

Using a CTE is a performance superstar.

Check out the link, it will explain how.

I admit the work to accomplish it is more.

But the result is milliseconds over millions of rows.

like image 32
Jerry Nixon Avatar answered Sep 23 '22 23:09

Jerry Nixon