You must Sign In to post a response.
  • Category: SQL Server

    GROUP BY in SQL Query

    Hi,
    I have SQL value like:

    BandName Style
    Band-1 A1
    Band-2 A2
    Band-2 A3
    Band-2 A4
    Band-3 A5
    Band-4 A6

    My desired Output is:

    BandName Style
    Band-1 A1
    Band-2 A2/A3/A4
    Band-3 A5
    Band-4 A6

    Please tell me how can I write a SQL Query for my desired output.
  • #749413
    Hi Ram Prasad,

    Try below query and see if this is the one you are looking for. Let me know if this doesn't help or you are searching for something else.

    SELECT BandName, Style =
    STUFF((SELECT ', ' + Style
    FROM your_table b
    WHERE b.BandName = a.BandName
    FOR XML PATH('')), 1, 2, '')
    FROM tblName a
    GROUP BY BandName


    Regards,
    Asheej T K

  • #749431
    Try below one

    DECLARE @Table1 TABLE(BandName varchar(10), Style varchar(10))
    INSERT INTO @Table1 VALUES ('Band-1',' A1'),('Band-2',' A2'),('Band-2',' A3'),('Band-2',' A4'),('Band-3',' A5'),('Band-4',' A6')



    SELECT BandName
    ,STUFF((SELECT '/ ' + CAST(Style AS VARCHAR(10)) [text()]
    FROM @Table1
    WHERE BandName = t.BandName
    FOR XML PATH(''), TYPE)
    .value('.','NVARCHAR(MAX)'),1,2,' ') Style
    FROM @Table1 t
    GROUP BY BandName

  • #749509
    Thanks Asheej & SivS for your valuable responses.
    Thanks,
    Ram Prasad

  • #749656
    Hello Ram Prasad,

    You have thanked to Asheej & SivS that is appriciable but you didn't mantioned that which solution has solved your issue? make habbit to choose answer as best answer when any answer solve your issue. if above answer does not solve your isuue than you can ask for further help.

    Regards,
    Nirav Prabtani (Senior Web Developer)
    Email : niravjprabtani@gmail.com
    blog : niravprabtani.blogspot.in


  • Sign In to post your comments