clubbing a group of column values orderwise

  • Hi,

    could you please help me to get a T-SQL statement for a scenario where

    if there is a table with values as

    type name email

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

    Administrator a a@abc.com

    Administrator b b@abc.com

    User x x@abc.com

    User y y@abc.com

    User z z@abc.com

    how do i compose the sql, it should display

    Administrator a@abc.com; b@abc.com

    User x@abc.com; y@abc.com; z@abc.com

  • What are you going to do with those strings once you have created them? It should really be a process for your presentation layer to loop through the results set and append the values togeter.

    If you really want to do it SQL you will need to use CURSORS but they are generally to be avoided.

    you could also do it using the PIVOT syntax and dynamic SQL but it would be ugly and slow(ish)

  • Mine is not to question why, only to do it without CURSORs:

    DECLARE @U TABLE (type VARCHAR(25), VARCHAR(10), email VARCHAR(100))

    INSERT INTO @U (type, , email)

    SELECT 'Administrator','a','a@abc.com'

    UNION ALL SELECT 'Administrator','b','b@abc.com'

    UNION ALL SELECT 'User','x','x@abc.com'

    UNION ALL SELECT 'User','y','y@abc.com'

    UNION ALL SELECT 'User','z','z@abc.com'

    SELECT type

    ,(SELECT stuff( (select '; ' + email

    from @U u2 WHERE u1.type = u2.type

    for xml path('')), 1, 1, '') ) AS emails

    FROM @U u1

    GROUP BY type


    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

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

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