sqlsql-serverssmsstuff

STUFF FOR XML PATH - combine multiple rows into a single column cell


Let's say I have data in a table that looks like this

   Num1        Type1        Type2       Acct        Ind
   ---         ----         ----        ---         ---
   1X2         XXX          CA          111         ERROR
   1X2         XXX          CA          222         ERROR

   X22         XXX          CA          111         ERROR
   X22         XXX          CA          222         ERROR
   X22         XXX          CA          333         ERROR
   X22         XXX          CA          444         ERROR

What I am trying to achieve is to add a new column, and eventually achieve something like this:

   Num1        Type1        Type2       Acct        Ind         Acct_List
   ---         ----         ----        ---         ---         --------
   1X2         XXX          CA          111         ERROR       111,222
   1X2         XXX          CA          222         ERROR       111,222

   X22         XXX          CA          111         ERROR       111,222,333,444
   X22         XXX          CA          222         ERROR       111,222,333,444
   X22         XXX          CA          333         ERROR       111,222,333,444
   X22         XXX          CA          444         ERROR       111,222,333,444

I attempted to do something like this:

    SELECT Num1, Type1, Type2, Acct, Ind, 'Acct_List' = STUFF((SELECT ', ' + CAST(ACCT AS VARCHAR(55)) FROM Table FOR XML PATH (''),1,1,'')
    FROM Table
    WHERE IND='ERROR'
    GROUP BY Num1, Type1, Type2, IND

However with this code what happens is that, each line, returns all the ACCT's in the ACCT_LIST

Is there any way to get this to look like the results data?


Solution

  • you are missing where clause:

    SELECT Num1, Type1, Type2, Acct, Ind, 'Acct_List' = STUFF((SELECT ', ' + CAST(ACCT AS VARCHAR(55)) FROM Table t1 WHERE t1.Num1 = t2.Num1 FOR XML PATH (''),1,1,'')
    FROM Table t2
    WHERE IND='ERROR'
    GROUP BY Num1, Type1, Type2, IND