op:group-to-arrays( $plan as map:map, $groups as item()+, [$aggregates as item()*] ) as map:map
This method performs multiple group-by operations on a row set and produces a single row with a column for each group having an array value whose items are the rows for the group. Each item is an object with properties for the group keys and aggregates.
The aggregates for the operation are specified as the second parameter instead of in a op:select operation (unlike SQL).
Parameters | |
---|---|
$plan | The Optic Plan. You can either use the XQuery => chaining operator or specify the variable that captures the return value from the previous operation. |
$groups |
The sets of grouping keys. Each group is specified with the
op:named-group function. Each group must have
a unique set of keys but multiple groups can have the same key.
As a convenience, the parameter also accepts unnamed groups with the op:group, op:rollup, or op:cube functions or (for a group with a single key) a column named with a string or a column parameter function such as op:col or constructed from an expression with the op:as function. The row objects produced by the group-to-arrays operation include the key columns from each group. A group can be empty to group over all of the rows in the row set. |
$aggregates | This parameter specifies either columns to sample or aggregate functions to apply to a column for all of the rows in the group. Sampled columns can be existing columns or new columns created by an expression specified with op:as. Often a sampled column might have a constant value within the group such as a title or label closely associated with a numeric identifier used as the grouping key. |
The group-to-arrays operation differs from the group-by operation as follows:
(: Calculate the total expenses separately for each category and for each location. :) xquery version "1.0-ml"; import module namespace op="http://marklogic.com/optic" at "/MarkLogic/optic.xqy"; op:from-view("main", "expenses") => op:group-to-arrays( (op:named-group("CategoryTotal", "Category"), op:named-group("LocationTotal", "Location"), op:named-group("AllTotal") ), op:sum("TotalAmount", "Amount") ) => op:result()