SQLSERVER将多行合并为一行

时间:2017-11-22 17:55:47

标签: sql-server

我有以下表格:

Product_Order
Order_Num   Order_Date
1           10/12/2017
2           10/31/2017
3           11/01/2017

Product_Order_Dtl
Order_Num   Product_Desc
1           Toy_01
1           Toy_02
1           Toy_03
2           Toy_01
2           Toy_05
3           Toy_01

我正在尝试更新Product Order表,将与该订单相关联的所有产品列入名为Product_List的新列。如下所示:

Product_Order
Order_Num   Order_Date  Product_List
1           10/12/2017  Toy_01, Toy_02, Toy_03
2           10/31/2017  Toy_01, Toy_05
3           11/01/2017  Toy_01

有没有办法使用更新语句?我使用的是SQL 2012版本。

2 个答案:

答案 0 :(得分:3)

您可以使用以下查询

SELECT A.Order_Num, A.Order_Date, STUFF((SELECT ',' + Product_Desc
          FROM Product_Order_Dtl C
where C.Order_Num=A.Order_Num            
          FOR XML PATH('')), 1, 1, '') AS Product_List
from Product_Order A
inner join Product_Order_Dtl B on A.Order_Num =B.Order_Num 
group by A.Order_Num,A.Order_Date

答案 1 :(得分:0)

这样做:

SELECT
    PO.Order_Num
    , PO.Order_Date
    ,
        STUFF
        (
            (
                SELECT ', ' + POD.Product_Desc
                FROM Product_Order_Dtl POD
                WHERE POD.Order_Num = PO.Order_Num
                ORDER BY POD.Product_Desc
                FOR XML PATH ('')
            ), 1, 2, ''
        ) Product_List
FROM Product_Order PO