1

我有一个基本架构,如下所示

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

我可以通过使用游标来获得此结果,但据我所知,游标会降低性能,那么获得此结果的更好方法是什么?

4

1 回答 1

4

询问:

SQLFIDDLE示例

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 |
于 2013-02-01T10:07:22.210 回答