我有一个类似于下面的基本架构
OrderTable
Id int
1
2
OrderDetailTable
Id int - OrderId int
1 1
2 1
3 1
4 1
5 2
6 2
7 2
我想要一张
的表格OrderOrderDetailCombinationTable
Order int - OrderDetails varchar(100)
实施例
Order - OrderDetails
1 1,2,3,4
2 5,6,7
http://www.sqlfiddle.com/#!3/c617b/2
我可以通过使用游标来获得此结果,但是我知道游标的性能会受到影响,那么获得此结果的更好方法是什么?
答案 0 :(得分:4)
查询:
<强> SQLFIDDLEEXample 强>
SELECT o.orderid AS [Order],
STUFF(( SELECT ',' +CAST( x.id as varchar(2) )
FROM orderdetail x
WHERE o.orderid = x.orderid
FOR XML PATH ('')
),1,1,'') as OrderDetails
FROM [orderdetail] o
INNER JOIN [order] oo
ON oo.id = o.orderid
GROUP BY o.orderid
结果:
| ORDER | ORDERDETAILS |
------------------------
| 1 | 1,2,3,4 |
| 2 | 5,6,7 |