1

I have this SQL query

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');

This query produces such data:

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

I want to delete duplicate elements, exactly the second node. The query must generate data without the duplicates

2
  • 1
    You already provided current output of your query. What's missing now is sample input data, can you provide it? Sample in sqlfiddle.com would be perfect Commented May 21, 2015 at 23:46
  • 1
    This is my data sqlfiddle.com/#!6/9eecb7db59d16c80417c72d1/1177 Commented May 22, 2015 at 8:17

1 Answer 1

1

Selecting distinct City before constructing the XML would be more efficient. This is one possible way using Common Table Expression (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

Sign up to request clarification or add additional context in comments.

2 Comments

and how this query in Oracle?
That's a whole different question which I don't know the answer. Even if I know, this thread isn't the place to properly answer that question. Try to figure it out your self, then if you get stuck don't hesitate to open a new question. Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.