Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Concat SQL row into comma separated list

I’m having an issue trying to Concat a comma separator list within SQL when the data matches. I have a table with 6 columns. I want to check if the LicenceNumbers match and then conconcatenate the ItemsNumbers into a comma separator list if the LicenceNumbers are the same.

Here is the query I’ve, but its combines the return result as 2 but adds all licences to each row

SELECT DISTINCT
    w2.Order,
    w2.Customer, 
    w2.Contract, 
    w2.Licence, 
    w2.CSSNTName, 
    CASE 
        WHEN w2.Licence= w1.LicenceTHEN
        (SELECT '[' + STRING_AGG(ISNULL(Item, ' '), ',') FROM #WorkingTable2) + ']'
        ELSE '[' + w2.Item+ ']' 
    END AS Item
FROM 
    #WorkingTable2 w2 
    INNER JOIN #WorkingTable2 w1 ON w1.Licence= w2.Licence

Table

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

| Order || Customer || Contract || Licence || Item || CSSNT |
| ----- || -------- || -------- || ------- || ---- || ----- |
| 5762  || 5273     || 70703US  || 420D3   || 8.10 || ABC02 |
| 5762  || 5273     || 70703US  || 420D3   || 8.9  || ABC02 |                           
| 1234  || 1111     || 123US    || 1234    || 9.10 || ABC01 |

What Results I’m looking for

| Order || Customer || Contract || Licence || Item      || CSSNT |
| ----- || -------- || -------- || ------- || --------- || ----- |
| 5762  || 5273     || 70703US  || 420D3   || [8.9,8.10]|| ABC02 |                         
| 1234  || 1111     || 123US    || 1234    || [9.10]    || ABC01 |

>Solution :

You can use a simple aggregate/group by approach

Example

Declare @YourTable Table ([Order] varchar(50),[Customer] varchar(50),[Contract] varchar(50),[Licence] varchar(50),[Item] varchar(50),[CSSNT] varchar(50))
Insert Into @YourTable Values 
 (5762,5273,'70703US','420D3',8.10,'ABC02')
,(5762,5273,'70703US','420D3',8.9,'ABC02')
,(1234,1111,'123US','1234',9.10,'ABC01')
 
Select [Order]
      ,[Customer]
      ,[Contract]
      ,[Licence]
      ,[Item]   = concat('[',string_agg(item,','),']')
      ,[CSSNT]
 From @YourTable
 Group By [Order]
      ,[Customer]
      ,[Contract]
      ,[Licence]
      ,[CSSNT]

Results

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading