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

4

3 回答 3

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
于 2011-04-11T16:46:57.347 回答
1

尝试这个:

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
于 2011-04-11T16:45:49.157 回答
0

发现这篇关于这个主题的好文章。它向您展示了执行此操作的不同方法。

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

于 2011-07-28T16:38:13.167 回答