SQL & XML - 减少重复数据

SQL & XML - reducing duplicate data

使用FOR XML寻找减少重复数据的方法。

这是架构和数据:

create table #area (StateId int, State varchar(10), Population int)
go
insert into #area values (1, 'AZ', 10000)
go
create table #person (Id int, FirstName varchar(10), LastName varchar(10), StateFk int)
go
insert into #person values (1, 'Joe', 'Smith', 1), (2, 'Jane', 'Doe', 1)
go

select a.State as '@State'
    , a.Population as '@Population'
    , p.FirstName as 'Person/FirstName'
    , p.LastName as 'Person/LastName'
from #area a
inner join #person p on a.StateId = p.StateFk
where a.Id = 1
for xml path('Record'), root ('RecordSet')
go

结果如下:

<RecordSet>
  <Record State="AZ" Population="10000">
    <Person>
      <FirstName>Joe</FirstName>
      <LastName>Smith</LastName>
    </Person>
  </Record>
  <Record State="AZ" Population="10000">
    <Person>
      <FirstName>Jane</FirstName>
      <LastName>Doe</LastName>
    </Person>
  </Record>
</RecordSet>

但是由于#area数据是静态的,我想减少重复的数据。使用 FOR XML,我怎么写 ot 所以结果看起来像这样:

<RecordSet>
    <State>AZ</State>
    <Population>10000</Population>
    <Person>
        <FirstName>Joe</FirstName>
        <LastName>Smith</LastName>
    </Person>
    <Person>
        <FirstName>Jane</FirstName>
        <LastName>Doe</LastName>
    </Person>
</RecordSet>

或者这个:

<RecordSet State="AZ" Population="1000">
    <Person>
        <FirstName>Joe</FirstName>
        <LastName>Smith</LastName>
    </Person>
    <Person>
        <FirstName>Jane</FirstName>
        <LastName>Doe</LastName>
    </Person>
</RecordSet>

nm,用子查询解决了

select a.State as '@State'
    , a.Population as '@Population'
    , (select p.FirstName as 'Person/FirstName'
        , p.LastName as 'Person/LastName'
        from #person p 
        where p.stateFk = a.StateId
        for xml path('')
    ) as 'Persons'
from #area a
for xml path('Record'), root ('RecordSet')
go