根据列构建项目数组

时间:2018-04-27 01:41:55

标签: sql sql-server

我有这样的查询:

SELECT 
    MCU.UserName
    ,MCU.McUserId AS UserId
    ,O.OrderId
    ,PD.ProductId
    ,O.ShippingId
    ,PD.[Name] AS ProductName
    ,O.OrderDate
    ,O.Total
    ,O.Subtotal
    ,O.PaymentStatus
    ,O.OrderNumber
    ,O.[Type]
    ,O.CreatedBy
    ,O.ModifiedBy
     FROM SecurityMc.McUsers AS MCU
     INNER JOIN Store.[Order] AS O ON  MCU.McUserId = O.UserId
     INNER JOIN Store.OrderItem AS OI ON O.OrderId = OI.OrderId
     INNER JOIN Customer.Shipping AS CS ON O.ShippingId = CS.ShippingId
     INNER JOIN Product.ProductDetail AS PD ON OI.ProductId = PD.ProductId
     WHERE  O.[Type] = 'Order' AND O.IsDeleted = 0 AND 1 = LanguageId 

返回如下数据:

+--------+---------+-----------+-------------+
| UserId | OrderId | ProductId | ProductName |
+--------+---------+-----------+-------------+
|      1 |       3 |         1 | Dress       |
|      1 |       3 |         2 | Boots       |
|      1 |       3 |         3 | Socks       |
|      1 |       3 |         4 | Extension   |
+--------+---------+-----------+-------------+

正如您所看到的,它为每一行返回一个ProductName,但我想将它作为一个数组发送给您 可以看到它有相同的OrderId和UserId,如果OrderId是相同的,它可以连接ProductName并得到一些东西 像:

ProductName(1列):Dress,Boots,Socks,Extension

我怎样才能实现它?此致

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找的是STRING_AGG功能。 请检查this小提琴。

您也可以使用recursive query + window functions