<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet href="../../make-menu.xsl" type="text/xsl"?><html>
   <head>
      <this-is section="using-xquery" page="xquery11support" subpage="groupby"/>
      <!--
           Generated at 2010-10-29T18:20:48.427+01:00--><title>Saxonica: XSLT and XQuery Processing: Grouping</title>
      <meta name="coverage" content="Worldwide"/>
      <meta name="copyright" content="Copyright Saxonica Ltd"/>
      <meta name="title" content="Saxonica: XSLT and XQuery Processing: Grouping"/>
      <meta name="robots" content="noindex,nofollow"/>
      <link rel="stylesheet" href="../../saxondocs.css" type="text/css"/>
   </head>
   <body class="main">
      <h1>Grouping</h1>
      <p>A subset of the grouping syntax from the draft XQuery 3.0 specification is implemented. The <code>group by</code> clause
must be preceded in the FLWOR expression by (a) a single <code>for</code> clause, which selects the sequence to be grouped, and (b)
a single <code>let</code> clause, which defines the grouping key; the "group by" clause must name the variable that is declared in the
<code>let</code> clause. For example: <code>for $x in //employee let $k := $x/department group by $k return ...</code>.
Within the <code>return</code> clause, <code>$x</code> refers to the content of the current group, and <code>$k</code>
to the current grouping key.</p>
      <p>The clauses <code>where</code> and <code>order by</code> may optionally appear after the <code>group by</code>.
The sequence of clauses must therefore be: <code>FOR LET GROUP-BY WHERE? ORDER-BY? RETURN</code>.</p>
      <p>The following example groups employees by location, considering only those where the location is non-null:</p>
      <div class="codeblock"
           style="border: solid thin; background-color: #B1CCC7; padding: 2px">
         <pre>
            <code>
for $e in //employee
let $loc := $e/location
group by $loc
where exists($oc)
order by count($e)
return &lt;location name="{$loc}" count="{count($e)}"&gt;{$e}&lt;/location&gt;
</code>
         </pre>
      </div>
      <table width="100%">
         <tr>
            <td>
               <p align="right"><a class="nav" href="multiple-where.xml">Next</a></p>
            </td>
         </tr>
      </table>
   </body>
</html>