Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get multiple rows into one line as a string?

Tags:

sql

sql-server

I have two tables "one to many":

Table1

ID    Name
1     Abe
2     David
3     Orly

Table2

ID    email
1     [email protected]
1     [email protected]
1     [email protected]
2     [email protected]
2     [email protected]
3     [email protected]
3     [email protected]

I need an output like this:

1 Abe [email protected], [email protected], [email protected]
2 David [email protected], [email protected]
3 Orly [email protected], [email protected]

I know this won't work, because the inner SELECT is not a single string:

SELECT 
    ID, Name, 
    (SELECT email FROM Table2  WHERE Table2.ID = Table1.ID) AS emails 
FROM Table1

I tried to apply:

DECLARE @emails VARCHAR(999)

SELECT [ID],[Name], 
     (SELECT @emails = COALESCE(@emails + ', ', '') + [email] 
      FROM Table2) AS 'emails' 
FROM Table1

but with no luck.

How should this be solved?

Thanks.

like image 503
elarrow Avatar asked Oct 31 '11 19:10

elarrow


People also ask

How do I combine multiple rows of data into one row?

To merge two or more rows into one, here's what you need to do: Select the range of cells where you want to merge rows. Go to the Ablebits Data tab > Merge group, click the Merge Cells arrow, and then click Merge Rows into One.

How do I concatenate multiple rows into a single string in Oracle?

You can use listagg() to convert rows into a comma separated string.

How do I concatenate 3 columns in SQL?

To concatenate more than 2 fields with SQL, you can use CONCAT() or CONCAT_WS() function.


1 Answers

One of the neatest ways to achieve this is to combine For XML Path and STUFF as follows:

SELECT
    ID, Name, 
    Emails = STUFF((
        SELECT ', ' + Email FROM Table2 WHERE Table2.ID = Table1.ID
        FOR XML PATH ('')),1,2,'')
FROM Table1
like image 147
Jon Egerton Avatar answered Oct 05 '22 02:10

Jon Egerton