我有这个SQL查询
SELECT r.Address.value('(//City)[1]','VARCHAR(MAX)') "City/@Title" ,
(SELECT r1.FirstName , r1.SecondName
FROM Reader r1
where r.Address.value('(//City)[1]','VARCHAR(MAX)') = r1.Address.value('(//City)[1]','VARCHAR(MAX)')
FOR XML RAW('Reader'),TYPE) AS "City/Readers"
FROM Reader r
FOR XML PATH(''),ROOT('Cities');
此查询生成此类数据:
<Cities>
<City Title="New York">
<Readers>
<Reader FirstName="JON" SecondName="SHOW" />
<Reader FirstName="Poll" SecondName="Aeron" />
</Readers>
</City>
<City Title="New York">
<Readers>
<Reader FirstName="JON" SecondName="SHOW" />
<Reader FirstName="Poll" SecondName="Aeron" />
</Readers>
</City>
<City Title="Kharkiv">
<Readers>
<Reader FirstName="Slavik" SecondName="Romanov" />
</Readers>
</City>
<City Title="Boca Juniors">
<Readers>
<Reader FirstName="Julio " SecondName="Pedro" />
</Readers>
</City>
<City Title="London">
<Readers>
<Reader FirstName="Johnny " SecondName="Smith" />
</Readers>
</City>
</Cities>
我想删除重复的元素,完全是第二个节点。 查询必须生成没有重复项的数据
答案 0 :(得分:1)
在构造XML之前选择distinct City
会更有效率。这是使用公用表表达式(CTE)的一种可能方式:
;WITH Cities
AS(
SELECT DISTINCT r.Address.value('(//City)[1]','VARCHAR(MAX)') As City
FROM Reader r
)
SELECT
c.City "City/@Title",
(SELECT r1.FirstName , r1.SecondName
FROM Reader r1
where c.City = r1.Address.value('(//City)[1]','VARCHAR(MAX)')
FOR XML RAW('Reader'),TYPE) AS "City/Readers"
FROM Cities c
FOR XML PATH(''),ROOT('Cities');
<强> Fiddle Demo 强>