I want to concatenate multiple rows in one column. I found many examples in Internet but does not working for me. What am I doing wrong?
SELECT UserID,
STUFF((SELECT '; ' + Email.Email From Email where UserEmail.EmailID = Email.ID for xml path('')),1,1, '') AS Emails
From UserEmail
where UserID = 1
I'm still having the information like this
UserID Email
1 [email protected]
1 [email protected]
--EDIT--
Ok, I did this change but still having 2 rows. If I apply distinct this will fix my problem but why do I have to use distinct. The query must group it by itself.
SELECT UserID,
STUFF(( SELECT '; ' + ea.Email
From Email ea inner join UserMail ue_inner on ue_inner.EmailID = ea.ID
where
ue_inner.UserID = ue.UserID
for xml path('')), 1, 1, '')
AS Email
From UserEmail ue
where UserID = 1
Results
UserID Email
1 [email protected]; [email protected]
1 [email protected]; [email protected]