4

I have 2 tables:

SELECT UnitId FROM dbo.tblUnits

SELECT UnitId, WorkOrderNumber FROM dbo.tblWorkOrders

I need to display all UnitId's from dbo.tblUnits then in 1 column diplay all the WorkOrders seperated by a comma.

So here is some sample data: dbo.tblUnits:

UnitId
123
156
178

dbo.tblWorkOrders

UnitId WorkOrderNumber
123        1
123        2
156        4
178        5
178        9
178        10

I have to use the tblUnits table because I am pulling more data from it but the final result I want to show this:

UnitId   WorkOrderNumber
123         1,2
156         4 
178         5,9,10

Any Ideas?

Thanks

Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
user380432
  • 4,619
  • 16
  • 51
  • 62
  • possible duplicate of [Concatenate multiple rows](http://stackoverflow.com/questions/3197626/concatenate-multiple-rows) – JeffO Apr 11 '11 at 16:45

4 Answers4

4
select 
    UnitId, 
    stuff((select ', ' + convert(varchar, WorkOrderNumber) 
           from tblWorkOrders t2 where t1.UnitId = t2.UnitId 
           for xml path('')),
          1,2,'') WorkOrderNumbers
from tblWorkOrders t1
group by UnitId
Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
1

Try this:

SELECT
   t1.UnitId,
   substring((SELECT ( ', ' + WorkOrderNumber)
                           FROM tblWorkOrders t2
                           WHERE t1.UnitId= t2.UnitId
                           ORDER BY 
                              UnitId
                           FOR XML PATH( '' )
                          ), 3, 1000 ) as WorkOrderNumbers
FROM tblWorkOrders as t1
Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
0

Found this nice article about this very topic. It shows you different way to do this.

http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/

JkenshinN
  • 331
  • 2
  • 9
0
SELECT 
    UnitId, 
    STRING_AGG(WorkOrderNumber, ',')
FROM dbo.tblWorkOrders
GROUP BY UnitId

should give you the final result you showed.

Kent Munthe Caspersen
  • 5,918
  • 1
  • 35
  • 34