-4

我有三个表如下:

订购产品变体

Id  |   ProductVariantId
----------------------------------------
1   |   22 
2   |   23
3   |   24
4   |   25

产品变体

Id  |   ProductId
----------------------------------------
22  |   34
22  |   35
23  |   36
23  |   37
24  |   38
24  |   39

产品

Id  |   Product
----------------------------------------
34  |   KBDMouse800 
35  |   KBDMK250
36  |   LaptopCorei7
37  |   LaptopCorei5
38  |   BluetoothMouse1000
39  |   PresentorR800

我希望输出结果为:

OrderProductVariant.Id  |   Product
-----------------------------------------
1           |   KBDMouse800, KBDMK250
2           |   LaptopCorei7, LaptopCorei5
3           |   BluetoothMouse1000, PresentorR800
4

1 回答 1

2

当前查询将给出 table 中的所有记录OrderProductVariant。也许是时候弄清楚如何过滤不匹配的记录了。

SELECT  o.ID,
        STUFF((SELECT   ',' + ' ' + b.Product 
               FROM ProductVariant a
               INNER JOIN Product b ON a.ProductId = b.Id
               WHERE a.Id = o.ProductVariantId
               FOR XML PATH ('')), 1, 1, '')  AS ProductList
FROM    OrderProductVariant AS o
GROUP   BY o.ID, o.ProductVariantId
于 2013-03-17T10:42:59.250 回答