开发者

merge two rows in return query as one

I have a query that returns the people in a certain household, however the individuals show up in to separate rows, what 开发者_运维技巧i want to do is merge the two rows into one.

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)

Current results:

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

Desired results:

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

However if theres 3 people then it would need to merge all 3 and so on


Depending on the response to the question I asked above, below is a simple script that would compile the names into a string and then output the string (I don't have access to the syntax validator now so forgive any errors):

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


Provided you're using SQL Server 2005 or up, you might be able to use FOR XML PATH('') to concatenate the strings.

This should do what you want without having to do manual loops: edit: fixed up SQL to actually work (now I have access to 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)

This is pretty close to the format of data that you wanted.

it converts the data to XML (without any actual XML markup due to the PATH('')) and then joins it back to the header row.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜