使用SQL查询合并一条记录中的记录

时间:2013-12-09 11:24:34

标签: c# sql-server-2005

我想将具有相同用户ID的记录合并到一条记录中,并将它们与,

分开

例如我有2个这样的表:

向tblUsers:

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

tblPhone:

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

我需要返回这些结果的SQL查询:

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

任何建议?

4 个答案:

答案 0 :(得分:1)

此查询将完成工作

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

答案 1 :(得分:0)

试试这个:

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

SQLFiddle demo

答案 2 :(得分:0)

首先:tblPhone表的命名约定如下:

ID | UserId | Phone

其中UserId是您指向用户的链接,而ID是tblPhone拥有的主键。 (最好是身份种子)

使用该方法,您可以创建一个for循环来处理值

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

答案 3 :(得分: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