Duplicating rows caused by multiple email addresses

Will Faulkner 201 Reputation points
2020-10-23T14:01:08.92+00:00

Hello

I using SQL Server 2014.

I have two tables:

PersonInfo
EmailAd

which join on a reference number, so:

SELECT
Firstname, Lastname, refnumber, emailaddress
from PersonInfo PI
Left Join EmailAd EA on PI.Refnumber = EA.Refnumber

However some people have more than one email so the output is sometimes:

Firstname Lastname refnumber emailaddress

William Faulkner 1 will@xyz
William Faulkner 1 bill@xyz

and can be as many as 5 emails sometimes

My desired output would be:

Firstname Lastname refnumber emailaddress
William Faulkner 1 will@xyz , bill@xyz

basically a way of keeping all the data on one row, regardless of how many emails the person has in the system.

Please can you advise on a way I can achieve this?

Thanks

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,559 questions
{count} votes

Accepted answer
  1. Tom Cooper 8,466 Reputation points
    2020-10-23T14:39:59.957+00:00
    Select Distinct PI.Firstname, PI.Lastname, PI.refnumber,
      (Select Stuff(
        (Select ', ' + EA.emailaddress From EmailAd EA Where EA.refnumber = PI.refnumber 
        For XML Path(''),Type)
        .value('text()[1]','varchar(max)'),1,2,N'')) As emailaddress
    From PersonInfo PI;
    

    Tom


0 additional answers

Sort by: Most helpful