Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

sql server - SQL same unit between two tables needs order numbers in 1 cell

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...