0

我有一个具有以下结构 OrderItems 的表

    OrderId  ProductName  UnitPrice
      1      Harley         1.0
      1      Gloves         0.25
      2      Gloves         0.25


 By doing a select I would like to obtain something similar with :
<Order>
<OrderItem>
<OrderId>1</OrderId><ProductName>Harley</ProductName><UnitPrice>1.0</UnitPrice>
</OrderItem>
<OrderItem>
<OrderId>1</OrderId><ProductName>Gloves</ProductName><UnitPrice>0.25</UnitPrice>
</OrderItem>
</Order>

and 
<Order>
<OrderItem>
<OrderId>2</OrderId><ProductName>Gloves</ProductName><UnitPrice>0.25</UnitPrice>
</OrderItem>
</Order>

目前我被困在

SELECT 
  t2.OrderId, t2.ProductName, t2.UnitPrice  
       FROM OrderItems t2,OrderItems t1 where t2.OrderId = t1.OrderId
        FOR XML PATH('OrderItem') , ROOT('Order')
4

1 回答 1

2

DECLARE @OrderItems TABLE (OrderID INT, ProductName VARCHAR(50), UnitPrice MONEY)
INSERT @OrderItems VALUES (1, 'Harley', 1.0), (1, 'Gloves', 0.25), (2, 'Gloves', 0.25)

SELECT  (   SELECT  OrderID, ProductName, UnitPrice
            FROM    @OrderItems t2
            WHERE   t2.OrderID = t1.OrderID
            FOR XML PATH('OrderItem'), TYPE
        ) 
FROM    (SELECT DISTINCT OrderID FROM @OrderItems) t1 
FOR XML PATH('Order') , ROOT('Orders')

给出这个输出

<Orders>
  <Order>
    <OrderItem>
      <OrderID>1</OrderID>
      <ProductName>Harley</ProductName>
      <UnitPrice>1.0000</UnitPrice>
    </OrderItem>
    <OrderItem>
      <OrderID>1</OrderID>
      <ProductName>Gloves</ProductName>
      <UnitPrice>0.2500</UnitPrice>
    </OrderItem>
  </Order>
  <Order>
    <OrderItem>
      <OrderID>2</OrderID>
      <ProductName>Gloves</ProductName>
      <UnitPrice>0.2500</UnitPrice>
    </OrderItem>
  </Order>
</Orders>

我想这就是你所追求的。

SQL小提琴

于 2012-09-20T16:01:08.737 回答