我有两张桌子:
SELECT UnitId FROM dbo.tblUnits
SELECT UnitId, WorkOrderNumber FROM dbo.tblWorkOrders
我需要在dbo.tblUnits中显示所有UnitId,然后在1列中显示所有以逗号分隔的WorkOrders。
以下是一些示例数据: dbo.tblUnits:
UnitId
123
156
178
dbo.tblWorkOrders
UnitId WorkOrderNumber
123 1
123 2
156 4
178 5
178 9
178 10
我必须使用tblUnits表,因为我从中提取了更多数据,但最终结果我想要显示:
UnitId WorkOrderNumber
123 1,2
156 4
178 5,9,10
任何想法?
由于
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:0)
发现这篇关于这个主题的好文章。它向您展示了不同的方法。
http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/