Grouping

If you are used to SQL, then you might have been wondering what the equivalent to its DISTINCT and GROUP BY keywords is in XQuery FLOWR expressions. Well, SQL does not have one.

You can, however, get a fair amount of mileage from the distinct-values() function. Here is a query that groups videos according to who directed them:


              <movies>
               

                 {for $d in distinct-values(//director) return
               

                    <director name="{$d}">
               

                    { for $v in //video[director = $d] return
               

                       <title>{$v/title}</title>
               

                    }
               

                    </director>
               

                 }
               

              </movies>
               

            

This is not an ideal solution: apart from anything else, it depends heavily on the ability of the query processor to optimize the two nested loops to give good performance. But for the time being, this is all there is. This is an area where vendors are very likely to offer extensions to the language as defined by W3C.

Grouping was a notoriously weak point of XSLT 1.0, and the problem has been addressed with considerable success in the 2.0 version of the language. XQuery will likely follow suit.

 
Free Stylus Studio XML Training:
W3C Member