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]
.
SQL Fiddle
MS SQL Server 2012 Schema Setup:
Query 1:
Results: