Search code examples
sqlt-sqlgroup-byconcatenation

SQL - Multiple records in one row


I've trying to create a script that allows me to display multiples records in a one-row, group by a specific column. Below is the code that I worked on. I've done it in Power BI but now I need it on SQL Someone could help me how can I fix this, I appreciate:

MY CODE:

   B.WorkOrderCode,
   STUFF((SELECT '; ' + A.UserName 
          FROM [PanatrackerGP].[dbo].[User] AS A
          WHERE A.ProfileOid = B.ProfileOid
          FOR XML PATH('')), 1, 1, '') [USERS]
FROM [PanatrackerGP].[dbo].[TrxIssueInventory] AS B
WHERE B.WorkOrderCode = 'S12119' 
GROUP BY B.ProfileOid, B.WorkOrderCode
ORDER BY 1

------------------------------  OUTPUT  ----------------------------------------

WorkOrderCode  |      USERS

S12119         |   GM; FM; FO; GR; RG; TI
S12119         |   NC; BS; DNA; CS; JMAGGI; mj; fa; LR; lgm; MS; JPU
-----------------------------------------------------------------------

Only these users should be shown 

------------------------------TrxIssueInventory[TABLE]-----------------
WorkOrderCode |  CreateUserName

S12119        |      FO
S12119        |      lgm
-----------------------------------------------------------------------

-----------------------------GOAL OUTPUT---------------------------------
WorkOrderCode |  CreateUserName

S12119        |      FO ; lgm          
-----------------------------------------------------------------------

Thank You


Solution

  •     STUFF(
                (
                SELECT DISTINCT '; ' + CAST(CreateUserName AS VARCHAR (MAX))
                FROM [PanatrackerGP].[dbo].[TrxIssueInventory] 
                WHERE (WorkOrderCode = A.WorkOrderCode)
                FOR XML PATH ('')
                ),1,2,''
            ) AS [USERS]
    FROM [PanatrackerGP].[dbo].[TrxIssueInventory] AS A
    WHERE WorkOrderCode = 'S12119' 
    GROUP BY WorkOrderCode
    
    ------------------OUTPUT-----------------------
    WorkOrderCode     |       USERS
    S12119            |      FO; lgm
    
    
    Thank you all!