Display multiple row values in a single row.

  • Hi,

    Lets say, I have a table with Gender,Name and Age.

    Gender Name Age

    --------------------

    Male John 52

    Female Joe 33

    Male Jim 42

    I want the output to be like;

    Male John 52 Jim 42

    Female Joe 33

    can anybody help me this on SQL SERVER 2003...??

  • Like this:

    DECLARE @Names TABLE

    (Gender VARCHAR(6), Name VARCHAR(6), Age INT)

    INSERT INTO @Names

    SELECT 'Male','John', 52

    UNION ALL SELECT 'Female','Joe', 33

    UNION ALL SELECT 'Male','Jim',42

    SELECT Gender, Names=

    STUFF((

    SELECT ' ' + Name + ' ' + CAST(Age AS VARCHAR)

    FROM @Names b

    WHERE a.Gender = b.Gender

    FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)')

    ,1, 1, '')

    FROM @Names a


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • My way is very similare to Dwain's way, but I also added the distinct key word so there will be only 2 rows. I also didn't use the stuff function:

    DECLARE @Tbl TABLE (Gender char(6), Name varchar(20), Age tinyint)

    INSERT INTO @Tbl (Gender, Name, Age)

    SELECT 'Male', 'John', 52

    UNION ALL

    SELECT 'Female', 'Joe', 33

    UNION ALL

    SELECT 'Male', 'Jim', 42

    select distinct Gender,

    cast((select Name + ' ' + cast(Age as char(2)) + ' ' FROM @Tbl t1 where t1.Gender = t2.Gender for xml path('')) as varchar(max)) as Det

    from @Tbl t2

    Adi

    --------------------------------------------------------------
    To know how to ask questions and increase the chances of getting asnwers:
    http://www.sqlservercentral.com/articles/Best+Practices/61537/

    For better answers on performance questions, click on the following...
    http://www.sqlservercentral.com/articles/SQLServerCentral/66909/

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply