问题
I've been trying to use FOR XML without success to do the following.
Source table:
Country | ID | 1950 | 1955
-----------------------------------------------------
Country 1 | 1 | 2.43 | 2.55
Country 2 | 2 | 4.54 | 42.15
Desired output:
<locations>
<location>
<loc name='Country 1' id='1' />
<dub>
<data year='1950' value='2.43' />
<data year='1955' value='2.55' />
</dub>
</location>
<location>
<loc name='Country 2' id='2' />
<dub>
<data year='1950' value='4.54' />
<data year='1955' value='42.15' />
</dub>
</location>
</locations>
Will it be necessary to unpivot for the dub element? I wanted the simplest SQL query possible.
I think FOR XML is too difficult to use. You should be able to specify the hierarchy just using simple XPath on column names but it won't accept, for example, [dub/data/@year=1955/@value]
as the name of the column [1950]
.
回答1:
SQL Fiddle
MS SQL Server 2012 Schema Setup:
create table YourTable
(
Country varchar(20),
ID int,
[1950] numeric(5,2),
[1955] numeric(5,2)
)
insert into YourTable values
('Country 1', 1, 2.43, 2.55),
('Country 2', 2, 4.54, 42.15)
Query 1:
select T.Country as 'loc/@name',
T.ID as 'loc/@id',
(
select 1950 as 'data/@year',
T.[1950] as 'data/@value',
null,
1955 as 'data/@year',
T.[1955] as 'data/@value'
for xml path(''), type
) as dub
from YourTable as T
for xml path('location'), root('locations'), type
Results:
<locations>
<location>
<loc name="Country 1" id="1" />
<dub>
<data year="1950" value="2.43" />
<data year="1955" value="2.55" />
</dub>
</location>
<location>
<loc name="Country 2" id="2" />
<dub>
<data year="1950" value="4.54" />
<data year="1955" value="42.15" />
</dub>
</location>
</locations>
来源:https://stackoverflow.com/questions/23250367/sql-for-xml-multilevel-from-one-pivoted-table