T-SQL基于GROUP BY列创建嵌套XML

时间:2016-05-21 18:36:40

标签: sql-server xml tsql group-by nested

我的表数据如下所示:

CustomerID ProductCode ProductPrice
1           P001        1.20
1           P002        3.6
1           P003        5.3
2           P001         30
2           P003        20

我想使用T-SQL XML生成如下输出:

<Sales>
  <Customer id="1">
     <Sale>
        <ProductCode>P001</ProductCode>
        <Price>1.20</Price>
     </Sale>
     <Sale>
        <ProductCode>P002</ProductCode>
        <Price>3.6</Price>
     </Sale>
     <Sale>
        <ProductCode>P003</ProductCode>
        <Price>5.3</Price>
     </Sale>
  </Customer>
  <Customer id="2">
    <Sale>
         <ProductCode>P001</ProductCode>
         <Price>30</Price>
    </Sale>
    <Sale>
       <ProductCode>P003</ProductCode>
       <Price>20</Price>
    </Sale>
  </Customer>
</Sales>

我尝试过使用:

SELECT CustomerID as "@id"
      ProductCode as "Sale/ProductCode",
      ProducPrice as "Sale/ProductPrice"
FROM myTable as Sale
Order by CustID
FOR XML PATH('Customer'), ROOT('Sales'), ELEMENTS

我得到的输出并不完全是我想要的。我得到了:

<Sales>
  <Sale>
   <Customer id="1">
     <ProductCode>P001</ProductCode>
     <ProductPrice>1.2</ProductPrice>
   </Customer>
  </Sale>
  <Sale>
   <Customer id="1">
     <ProductCode>P002</ProductCode>
     <ProductPrice>3.6</ProductPrice>
   </Customer>
 </Sale>
 <Sale>
  <Customer id="1">
     <ProductCode>P003</ProductCode>
     <ProductPrice>5.3</ProductPrice>
  </Customer>
 </Sale>
 <Sale>
  <Customer id="2">
     <ProductCode>P001</ProductCode>
     <ProductPrice>30</ProductPrice>
  </Customer> 
 </Sale>
 <Sale>
   <Customer id="2">
     <ProductCode>P003</ProductCode>
     <ProductPrice>20</ProductPrice>
  </Customer>
 </Sale>
</Sales>

我不希望Customer标记继续如上所述。我想在其中只有一个带有嵌套销售的Customer标签。所以它有点像&#34; GROUP BY客户ID&#34;。我怎么能得到这个。非常感谢提前。

1 个答案:

答案 0 :(得分:5)

SELECT  CustomerID as "@id"
     , (SELECT ProductCode
              ,ProductPrice
        FROM TableName t
        WHERE Sale.CustomerID = t.CustomerID
        FOR XML PATH('Sale'), TYPE
       )
FROM (
Select DISTINCT CustomerID 
FROM TableName) as Sale
Order by CustomerID
FOR XML PATH('Customer'), ROOT('Sales'), ELEMENTS

<强>结果

<Sales>
  <Customer id="1">
    <Sale>
      <ProductCode>P001</ProductCode>
      <ProductPrice>1.20</ProductPrice>
    </Sale>
    <Sale>
      <ProductCode>P002</ProductCode>
      <ProductPrice>3.60</ProductPrice>
    </Sale>
    <Sale>
      <ProductCode>P003</ProductCode>
      <ProductPrice>5.30</ProductPrice>
    </Sale>
  </Customer>
  <Customer id="2">
    <Sale>
      <ProductCode>P001</ProductCode>
      <ProductPrice>30.00</ProductPrice>
    </Sale>
    <Sale>
      <ProductCode>P003</ProductCode>
      <ProductPrice>20.00</ProductPrice>
    </Sale>
  </Customer>
</Sales>