Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate many rows with same id in sql?

Tags:

sql

sql-server

My table contains the details like with two fields:

ID      DisplayName
1        Editor
1        Reviewer
7        EIC
7        Editor
7        Reviewer
7        Editor
19       EIC
19       Editor
19       Reviewer

I want get the unique details with DisplayName like

1 Editor,Reviewer 7 EIC,Editor,Reviewer

Don't get duplicate value with ID 7

How to combine DisplayName Details? How to write the Query?

like image 675
Luc Le Avatar asked Feb 03 '16 09:02

Luc Le


People also ask

How do I concatenate multiple row values in SQL?

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.

How do I sum rows with the same ID?

To sum rows with same ID, use the GROUP BY HAVING clause.

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

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.


1 Answers

In SQL-Server you can do it in the following:

QUERY

SELECT id, displayname = 
    STUFF((SELECT DISTINCT ', ' + displayname
           FROM #t b 
           WHERE b.id = a.id 
          FOR XML PATH('')), 1, 2, '')
FROM #t a
GROUP BY id

TEST DATA

create table #t 
(
id int,
displayname nvarchar(max)
)

insert into #t values    
 (1 ,'Editor')
,(1 ,'Reviewer')
,(7 ,'EIC')
,(7 ,'Editor')
,(7 ,'Reviewer')
,(7 ,'Editor')
,(19,'EIC')
,(19,'Editor')
,(19,'Reviewer')

OUTPUT

id  displayname
1   Editor, Reviewer
7   Editor, EIC, Reviewer
19  Editor, EIC, Reviewer
like image 124
Stanislovas Kalašnikovas Avatar answered Sep 18 '22 21:09

Stanislovas Kalašnikovas