0

我想使用in将行合并到单列FOR XML PATHSQL

这是我的查询:

select d.Device from tbl_Sales_OrderItems tsoi left join tbl_devices d 
on d.DeviceID=tsoi.DeviceID
where salesorderid=102 
and tsoi.Quantity>0
and tsoi.TypeID=1

union all

select d.Partnumber Device from tbl_Sales_OrderItems tsoi left join tbl_VendorParts d 
on d.VendorPartID=tsoi.RefID
where salesorderid=102 
and tsoi.Quantity>0
and tsoi.TypeID=2

在这里,我得到两行,即来自的两个设备名称tbl_Sales_Order

现在这些行我想在单行中使用FOR XML PATH到单列中。

进一步应用后FOR XML PATH,我想在select query我想使用它的行值中使用它,如下所示。

Select salesorderid,@resultinRow from tbl_Sales_Orders

输出要求:

SalesOrderID  Devices
  102          Device1,Device2
  103          Device3,Device2
4

1 回答 1

3

测试数据

DECLARE @TABLE TABLE (SalesOrderID INT, Devices VARCHAR(30))
INSERT INTO @TABLE VALUES
(102,'Device1'),
(102,'Device2'),
(103,'Device3'),
(103,'Device2')

询问

SELECT t.SalesOrderID
      , STUFF(( SELECT ', ' + Devices
                FROM @TABLE 
                WHERE SalesOrderID = t.SalesOrderID
                FOR XML PATH(''),TYPE)
                .value('.','NVARCHAR(MAX)'),1,2,'') AS Devices
FROM @TABLE t
GROUP BY t.SalesOrderID

结果集

╔══════════════╦══════════════════╗
║ SalesOrderID ║     Devices      ║
╠══════════════╬══════════════════╣
║          102 ║ Device1, Device2 ║
║          103 ║ Device3, Device2 ║
╚══════════════╩══════════════════╝
于 2014-05-07T09:14:31.920 回答