V
V
VMesser2019-04-26 10:27:08
SQL Server
VMesser, 2019-04-26 10:27:08

How to transform XML using XQuery?

How to implement the following XML processing using XQuery. I use in MSSQL.

View XML:
<ScheduleTable>
  <Schedule>
    <Year>2018</Year>
    <Item>Курочка</Item>
  </Schedule>
  <Schedule>
    <Year>2018</Year>
    <Item>Ряба</Item>
  </Schedule>
  <Schedule>
    <Year>2019</Year>
    <Item>Foo</Item>
  </Schedule>
  <Schedule>
    <Year>2019</Year>
    <Item>Bar</Item>
  </Schedule>
</ScheduleTable>

Convert to:
<MainSchedule>
  <YearSchedule>
    <Year>2018</Year>
      <YearItem>
        <Name>Курочка</Name>
      </YearItem>
      <YearItem>
        <Name>Ряба</Name>
      </YearItem>
  </YearSchedule>
  <YearSchedule>
    <Year>2019</Year>
      <YearItem>
        <Name>Foo</Name>
      </YearItem>
      <YearItem>
        <Name>Bar</Name>
      </YearItem>
  </YearSchedule>
</MainSchedule>


In fact, this means grouping the data by year.
I do it in MSSQL using FOR XML, the nodes() method with its subsequent quering. I learned how to display two unique years, but all 4 Item options are placed inside for each year. The problem remained in bringing the data from the desired year under the desired year.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Fov, 2019-04-26
@Roman-Fov

It's so simple. You need to select elements containing a specific year. You can do it like this (for 2018):
For others, just change the year and write where necessary

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question