1

I want to merge record with same user id into one record and separate them with ,

for example i have 2 tables like this:

tblUsers:

Id      Name
----------------
1       name1
2       name2
3       name3

tblPhone:

Id      Phone
-----------------
1       p11
1       p12
2       p21
2       p22
2       p23

I need sql query that return these results:

Id      Name      Phone
------------------------------
1       name1     p11,p12
2       name2     p21,p22,p23
3       name3     null

any suggestion?

HaMeD
  • 349
  • 1
  • 14

4 Answers4

1

This query will do the job

select u.Id, u.Name,
stuff((select ','+p.Phone 
       from tblPhone p 
       where p.Id = u.Id 
       for XML path('')),1,1,'')
from tblUsers u

SQL Fiddle demo

Szymon
  • 42,577
  • 16
  • 96
  • 114
0

Try this:

SELECT
   id,Name,
   STUFF((SELECT ','+Phone FROM tblPhone 
           WHERE id=tblusers.Id FOR XML PATH('')),1,1,'')
FROM 
   tblUsers 

SQLFiddle demo

valex
  • 23,966
  • 7
  • 43
  • 60
0

First of all: Naming conventions of your tblPhone table should be as follows:

ID | UserId | Phone

Where UserId is your link to the users and ID is the tblPhone own Primary key. (preferable a identity seed)

with that approach you can create a for loop for handling the values

DECLARE @table table(userid int, Phones(varchar(max))
DECLARE @min int = 1, @max int = select count(1) from tblPhone

DECLARE @userid int, @Phone varchar(50) 

for(@min <=@max)
BEGIN
  select @userid = UserId, @Phone = Phone from tblPhone where ID = @min
  if(@userid != null)
  BEGIN
    IF NOT EXIST(Select * from @table where userid = @userid)
    BEGIN
      --Create a line
      INSERT INTO @table
      VALUES(@userid, @Phone)
    END
    ELSE
    BEGIN
      --Update the line
      UPDATE @table
      Set Phone = Phone + ', ' + @Phone
      WHERE userid = @userid
    END
  END

SET @Min = @Min + 1
END

Select * from @table
Schuere
  • 1,579
  • 19
  • 33
0
SELECT Id,Name, Phone= 
STUFF((SELECT ', ' + Phone
       FROM tblPhone 
       WHERE tblUsers.id = tblPhone.id
      FOR XML PATH('')), 1, 2, '')
 FROM tblUsers
 GROUP BY id,Name
YOusaFZai
  • 698
  • 5
  • 21