1

我一直在尝试使用 FOR XML 来执行以下操作但没有成功。

源表:

Country            | ID      | 1950        | 1955
-----------------------------------------------------
Country 1          | 1       | 2.43        | 2.55
Country 2          | 2       | 4.54        | 42.15

期望的输出:

<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>

是否有必要为 dub 元素取消透视?我想要最简单的 SQL 查询。我觉得 FOR XML 太难用了。您应该能够仅在列名称上使用简单的 XPath 来指定层次结构,但它不会接受,例如,[dub/data/@year=1955/@value]作为列的名称[1950]

4

1 回答 1

2

SQL小提琴

MS SQL Server 2012 架构设置

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)

查询 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

结果

<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>
于 2014-04-23T18:26:40.683 回答