1

an XQuery query that calculates the average of the grades of each course, how i can do?

    <?xml-stylesheet href="class3.xsl" type="text/xsl" ?><school>
    <student><name>Jack T</name>
    <course title="INF8430" note="78"/>
    <course title="INF1030" note="69"/>
    <course title="INF1230" note="85"/></student>
    <student><name>Marty L</name>
    <course title="INF8430" note="95"/>
    <course title="INF1030" note="82"/>
    <course title="INF1230" note="77"/></student>
    <student><name>Ben L</name>
    <course title="INF9430" note="59"/>
    <course title="INF1030" note="78"/>
    <course title="INF1230" note="79"/></student>
    </school>

i do this but dnst work:

     for $s in distinct-values(doc("tesst.xml")//course/@title)
    return
     avg(doc("tesst.xml")//course[@title=$s]/@note)
     <course title="{$s},"></course>

to get this:

<maliste>
       <cours sigle="INF8430">85</cours>
       <cours sigle="INF1030">76.66666666666667</cours>
       <cours sigle="INF1230">81.5</cours>
       <cours sigle="INF9430">39</cours>
    </maliste>

an XQuery query that calculates the average of the grades of each course, how i can do?

david9999
  • 19
  • 1

1 Answers1

2

That sounds like a typical grouping/aggregation problem:

<malist>
{
  for $course in //course
  group by $title := $course/@title
  return
    <cours sigle="{$title}">{format-number(avg($course/@note), '0.00')}</cours>
}
</malist>

In XQuery, grouping results might be in any order, if you want to preserve the input order use e.g.

<malist>
{
  for $course at $p in //course
  group by $title := $course/@title
  order by $p[1]
  return
    <cours sigle="{$title}">{format-number(avg($course/@note), '0.00')}</cours>
}
</malist>
Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
  • 86.50 76.33 80.33 59.00 i found this, but the average is not good. soorry to ask but how i can do it plz – david9999 Oct 01 '22 at 15:23
  • @david9999, I don't understand what you complain about. The values you showed in your question don't seem to be the right values e.g. there is a single ``, I don't see why the average would be `39`. – Martin Honnen Oct 01 '22 at 15:28
  • soryy my bad, my mystak. you right. thx very much – david9999 Oct 01 '22 at 15:33