botbook/src/06-gbdialog/keyword-group-by.md

3.6 KiB

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

Parameter Type Description
data Array The data array to group
column String Column name to group by
aggregates Object Optional 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:

Property Description
key The grouping value
items Array of items in this group
count Number of items in group
Additional Any requested aggregates

Supported Aggregates

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

Sample Conversation

Show me sales by region

14:30

📊 Sales by Region (2025)

North America: $245,000 (127 sales)

Europe: $189,500 (98 sales)

Asia Pacific: $156,200 (84 sales)

Latin America: $67,300 (42 sales)

14:30

See Also

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