2011-09-30 55 views
1

我有以下行:級聯分組SQL行插入XML節點

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> 

任何想法如何解決這個?

謝謝!

回答

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') 
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 
+0

在這個問題上列出的列是唯一一個example.But你是對的。 –