级联将sql行分组到Xml节点中

时间:2011-09-30 11:10:26

标签: sql xml rows cascade

我有以下几行:

ID|Customer | Part Number | Part Number Price | Hardware ID | Hardware Value
------------------------------------------------------------------------------
1 | John    |     15      |       10          |      1      | 1000
2 | John    |     16      |       15          |      2      | 500

我试图进入SQL Server的输出如下:

<Order>
 <Customer>John</Customer>
 <PartNumbers>
  <PartNumber>15</PartNumber><PartNumberPrice>10</PartNumberPrice>  
  <PartNumber>16</PartNumber><PartNumberPrice>15</PartNumberPrice>  
 </PartNumbers>
 <Hardware>
  <HardwareId>1</HardwareId><HardwareValue>1000</HardwareValue>
  <HardwareId>1</HardwareId><HardwareValue>500</HardwareValue>
 </Hardware>
</Orders>

知道如何解决这个问题吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

对于自联接,这看起来有点滑稽,但这只是因为您的表没有正确规范化。您可能还想考虑没有空格的列名。

SELECT Customer as Customer,
      (SELECT DISTINCT o.[Part Number] partNumber,o.[Part Number Price] PartNumberPrice
       FROM yTable o
       where t.id = o.id
       FOR XML AUTO, TYPE),
      (SELECT DISTINCT x.[Hardware ID] hardwareid,x.[Hardware Value] hardwarevalue
       FROM yTable x
       where t.id = x.id
       FOR XML AUTO, TYPE)
FROM yTable t
FOR XML AUTO, TYPE

答案 1 :(得分:1)

declare @T table
(
  ID int,
  Customer varchar(10),
  [Part Number] int,
  [Part Number Price] int,
  [Hardware ID] int,
  [Hardware Value] int
)

insert into @T values
(1, 'John', 15, 10, 1, 1000),
(2, 'John', 16, 15, 2, 500)

select T1.Customer as Customer,
       (select T2.[Part Number] as PartNumber,
               T2.[Part Number Price] as PartNumberPrice
        from @T as T2
        where T1.Customer = T2.Customer       
        for xml path(''), root('PartNumbers'), type),
       (select T2.[Hardware ID] as HardwareId,
               T2.[Hardware Value] as HardwareValue
        from @T as T2
        where T1.Customer = T2.Customer       
        for xml path(''), root('Hardware'), type)
from @T as T1
group by T1.Customer
for xml path(''), root('Order')