Xquery group by on 2 tags

家住魔仙堡 提交于 2020-01-03 18:02:46

问题


Below is the XML part of my data.

<A>
 <a><Type>Fruit</Type><Name>Banana</Name></a>
 <a><Type>Fruit</Type><Name>Orange</Name></a>
 <a><Type>Fruit</Type><Name>Apple</Name></a>
 <a><Type>Fruit</Type><Name>Lemon</Name></a>
 <a><Type>Cars</Type><Name>Toyota</Name></a>
 <a><Type>Cars</Type><Name>Lamborghini</Name></a>
 <a><Type>Cars</Type><Name>Renault</Name></a>
</A>

Out put as -

<a>Fruits-Banana,Orange,Apple,Lemon</a>
<a>Cars-Toyota,Lamborghini,Renault</a>

I tried to get the required output by all in vain. I tried 'group by` clause too, but getting errors.

any help?


回答1:


let $x:=
<A>
  <a><Type>Fruit</Type><Name>Banana</Name></a>
  <a><Type>Fruit</Type><Name>Orange</Name></a>
  <a><Type>Fruit</Type><Name>Apple</Name></a>
  <a><Type>Fruit</Type><Name>Lemon</Name></a>
  <a><Type>Cars</Type><Name>Toyota</Name></a>
  <a><Type>Cars</Type><Name>Lamborghini</Name></a>
  <a><Type>Cars</Type><Name>Renault</Name></a>
</A>

  for $z in distinct-values($x//a/Type)
    let $c := $x//a[Type=$z]/Name
    return
       <a>{concat($z, "-", string-join($c, ","))}</a>

First for is taking the distinct values of the tag Type, then for each distinct value of this, the respective values of all the Name tags are derived.

Then using the concat function I have concatenated the Type text with the string generated by string-join, used to add/append the Name and , (comma).

HTH :)



来源:https://stackoverflow.com/questions/21284293/xquery-group-by-on-2-tags

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!