Combine Multiple Rows into One Row using SQL Server

Imagine you have a column like this:

Numbers
---------
One
Two
Three
Four
Five

The output you desire is to combine all the rows and put it as one row similar to the following:

OneTwoThreeFourFive


Let us see how to do it:

-- Sample Script to create the table and insert rows
-- By SQLServerCurry.com

CREATE TABLE #Temp
(
[Numbers] varchar(40)
)
INSERT INTO #Temp VALUES('One');
INSERT INTO #Temp VALUES('Two');
INSERT INTO #Temp VALUES('Three');
INSERT INTO #Temp VALUES('Four');
INSERT INTO #Temp VALUES('Five');



-- Query to combine multiple rows into one

DECLARE @str VARCHAR(100)
SELECT @str = COALESCE(@str + '', '') + [Numbers]
FROM #Temp
Print @str

You can also achieve the same result using STUFF

SELECT DISTINCT STUFF( (SELECT '*' + Numbers from #Temp FOR XML PATH('')),1,1,'') as Numbers FROM #Temp

Update: Here's another solution if you want to combine and output multiple rows as CSV - SQL Server: Combine Multiple Rows Into One Column with CSV output

20 comments:

  1. Nice! I like the XML technique :)

    ReplyDelete
  2. briliant !
    what if we only want the distinct values ?
    say... we have 2 values of "two" and we only want to print One|Two|Three|Four|Five. not One|Two|Two|Two|Three|Four|Five.
    where do i have to place the distinct keyword ?

    ReplyDelete
  3. thanks working perfect , mainly xml stuff

    ReplyDelete
  4. Thanks a lot. Your solution helped me in making a query.

    ReplyDelete
  5. Its good...
    But wat if i want to use integer instead of varchar???

    This wud not work...
    Wat to do in that cae??

    ReplyDelete
  6. but what do i have to do in case that strings are replaced with numbers??

    ReplyDelete
  7. Ramya raj and shyam,

    You need to convert the number to varchar

    ReplyDelete
  8. This will not work when the sql statement contains a JOIN.

    For example:
    DECLARE @str VARCHAR(100)

    SELECT
    SQLCUS_CRM.DESCRIPTION,
    @str = COALESCE(@str + '|', '') + cast(cuscrmid as varchar(10))
    FROM SQLCUS_CRM
    LEFT JOIN SQLCUS_CRMUSER ON SQLCUS_CRMUSER.CUSCRMID = SQLCUS_CRM.ID
    Print @str

    Will throw an error:
    A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.

    Is there any solution for this ?

    ReplyDelete
  9. Anonymous said...
    November 13, 2008 5:14 AM
    briliant !
    what if we only want the distinct values ?
    say... we have 2 values of "two" and we only want to print One|Two|Three|Four|Five. not One|Two|Two|Two|Three|Four|Five.
    where do i have to place the distinct keyword ?

    Never got a reply for this.

    ReplyDelete
  10. Anonymous, here are the methods that return unique values

    DECLARE @str VARCHAR(100)
    SELECT @str = COALESCE(@str + '|', '') + [Numbers]
    FROM (select distinct [numbers] from #Temp) as t
    Print @str

    SELECT DISTINCT STUFF( (SELECT distinct '*' + Numbers from #Temp FOR XML PATH('')),1,1,'') as Numbers FROM #Temp

    ReplyDelete
  11. I have two COLUMNS

    Col1 | Col2
    A | A1
    A | A2
    A | A3
    A | A4
    A | A5
    B | B1
    B | B2
    B | B3
    B | B4
    C | C1
    C | C2
    C | C3


    I need my results TO be

    Col1 | Col2
    A | A1,A2,A3,A4,A5
    B | B1,B2,B3,B4
    C | C1,C2,C3

    How will I get this. I am in learning phase of T-SQL sorry if its too basic question to paste, and I am using sql 2008 varchar (40). I need some here please.
    I tried some options with Group by and using STUFF but I am not getting the exact one.

    ReplyDelete
  12. Pramod: Your requirement can be achived in three ways: FORXML, a PIVOT operator or CLR aggregation function. I will use FORXML and post the answer in a couple of hours as soon as I have access to my machine.

    Stay tuned!

    ReplyDelete
  13. how if update 2 table with multiple row
    table 1
    id,
    name,
    address

    table 2
    id,
    id_one
    hobby
    phone

    sampel if someone have 1 name but have 2 hobby n phone

    how update table 2 ???

    ReplyDelete
  14. hi I have one table in which have employee_id, manager_id and Employee_Name.

    Employee 1st Have no Manager and employee 1st is the Manager of Employee 2nd.
    and now show the result in table in which field is employee_id, employee_name and Manager_Name

    ReplyDelete