Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

GROUP BY

Groups data by specified columns and optionally applies aggregate functions.

Syntax

result = GROUP BY data, column
result = GROUP BY data, column, aggregates

Parameters

ParameterTypeDescription
dataArrayThe data array to group
columnStringColumn name to group by
aggregatesObjectOptional aggregate functions to apply

Description

GROUP BY organizes rows of data into groups based on matching values in a specified column. When combined with aggregate functions, it calculates summary values for each group.

Examples

Basic Grouping

orders = FIND "orders", "status=completed"
grouped = GROUP BY orders, "category"

FOR EACH group IN grouped
    TALK "Category: " + group.key + " - Count: " + group.count
NEXT

With Aggregates

sales = FIND "sales", "year=2025"
summary = GROUP BY sales, "region", #{
    total: "SUM(amount)",
    average: "AVG(amount)",
    count: "COUNT(*)"
}

FOR EACH region IN summary
    TALK region.key + ": $" + region.total + " (" + region.count + " sales)"
NEXT

Multiple Level Grouping

' First group by category, then by month
products = FIND "orders", "year=2025"
by_category = GROUP BY products, "category"

FOR EACH cat IN by_category
    TALK "Category: " + cat.key
    by_month = GROUP BY cat.items, "month"
    FOR EACH month IN by_month
        TALK "  " + month.key + ": " + month.count + " orders"
    NEXT
NEXT

Return Value

Returns an array of group objects, each containing:

PropertyDescription
keyThe grouping value
itemsArray of items in this group
countNumber of items in group
AdditionalAny requested aggregates

Supported Aggregates

FunctionDescription
SUM(column)Sum of values
AVG(column)Average of values
MIN(column)Minimum value
MAX(column)Maximum value
COUNT(*)Number of rows

Sample Conversation

See Also

  • AGGREGATE - Single aggregate calculations
  • PIVOT - Cross-tabulation of data
  • FILTER - Filter data before grouping
  • FIND - Retrieve data to group