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

Cea*_*sar 3 xml t-sql sql-server nested group-by

我有这样的表数据:

CustomerID ProductCode ProductPrice
1           P001        1.20
1           P002        3.6
1           P003        5.3
2           P001         30
2           P003        20
Run Code Online (Sandbox Code Playgroud)

我想使用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>
Run Code Online (Sandbox Code Playgroud)

我尝试过使用:

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
Run Code Online (Sandbox Code Playgroud)

我得到的输出并不完全是我想要的.我正进入(状态:

<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>
Run Code Online (Sandbox Code Playgroud)

我不希望Customer标记继续如上所述.我想在其中只有一个带有嵌套销售的Customer标签.所以它有点像"GROUP BY Customer ID".我怎么能得到这个.提前谢谢了.

M.A*_*Ali 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
Run Code Online (Sandbox Code Playgroud)

结果

<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>
Run Code Online (Sandbox Code Playgroud)