将返回查询中的两行合并为一行

时间:2011-08-06 01:09:41

标签: sql sql-server-2005

我有一个返回特定家庭中的人的查询,但是个人出现在单独的行中,我想要做的是将两行合并为一行。

SELECT     dbo.households.id, dbo.individuals.firstname, dbo.individuals.lastname
FROM         dbo.households INNER JOIN
                      dbo.individuals ON dbo.households.id = dbo.individuals.householdID
WHERE     (dbo.households.id = 10017)

目前的结果:

ID | First Name | Last Name |
1  | Test       | Test1     |
1  | ABC        | ABC1      |

期望的结果:

ID | First Name | Last Name |ID1| First Name1| Last Name1|
1  | Test       | Test1     |1  | ABC        | ABC1      |

然而,如果有3个人那么它将需要合并所有3个等等

2 个答案:

答案 0 :(得分:1)

根据我上面提到的问题的响应,下面是一个简单的脚本,它将名称编译成一个字符串,然后输出字符串(我现在无法访问语法验证器,所以原谅任何错误):

DECLARE 
    @CNT INT,
    @R_MAX INT,
    @H_ID INT,
    @R_FIRST VARCHAR(250),
    @R_LAST VARCHAR(250),
    @R_NAMES VARCHAR(MAX)

SET @CNT = 0; --Counter
SET @R_NAMES = 'Names: ';
SELECT @R_MAX = COUNT(*) FROM dbo.individuals a WHERE a.householdID = @H_ID; --Get total number of individuals
PRINT(@R_MAX); --Output # of matching rows
--Loop through table to get individuals
WHILE @CNT < @R_MAX
    BEGIN
        --Select statement
        SELECT * FROM (SELECT
            @R_FIRST = b.firstname,
            @R_LAST = b.lastname,
                       ROW_NUMBER() OVER (ORDER BY b.lastname, b.firstname) AS Row
        FROM
            dbo.households a INNER JOIN
            dbo.individuals b ON a.id = b.householdID 
        WHERE
            (a.id = @H_ID)) AS RN WHERE (Row = @CNT);

        SET @R_NAMES = @R_NAMES + @R_FIRST + @R_LAST + '; '; --Add individual's name to name string
              PRINT(CAST(@CNT AS VARCHAR) + ':' + @R_NAMES);
        SET @CNT = @CNT +1; --Increase counter
    END

PRINT(@R_NAMES); --Output the individuals

答案 1 :(得分:1)

如果您使用的是SQL Server 2005或更高版本,则可以使用FOR XML PATH('')来连接字符串。

这应该做你想要的而不必手动循环: 编辑:修复SQL实际工作(现在我可以访问SQL)

SELECT households.id, 
  STUFF(
    (
      SELECT '; ' + [firstname] + '|' + lastname AS [text()]
      FROM individuals
      WHERE individuals.householdID = households.id
      FOR XML PATH('')
    )
    , 1, 2, '' ) -- remove the first '; ' from the string
  AS [name]
FROM dbo.households
WHERE (households.id = 10017)

这非常接近您想要的数据格式。

它将数据转换为XML(由于PATH('')而没有任何实际的XML标记),然后将其连接回标题行。