Description
Aggregates MAP values by summing numeric values for matching keys across multiple rows. This function is inspired by ClickHouse’s sumMap and is particularly useful for data aggregation scenarios involving maps with numeric values. Given multiple maps with the same key type and numeric value type,sum_map merges them by:
- Collecting all unique keys from all input maps
- Summing the values for each key across all maps
- Returning a single map with the aggregated results
Syntax
Parameters
map_expr: A MAP expression where the value type must be numeric (TINYINT, SMALLINT, INT, BIGINT, LARGEINT, FLOAT, or DOUBLE). Both keys and values can be nullable.
Return value
Returns a MAP with the same key and value types as the input, containing all unique keys and their summed values.NULL Handling
Thesum_map function handles NULL keys and values according to the following rules:
- NULL values: Entries with NULL values are excluded from the aggregation, regardless of whether the key is NULL or not.
- NULL keys: Entries with NULL keys but non-NULL values are included in the result as
{NULL: aggregated_value}. - NULL maps: NULL map inputs (i.e., the entire map is NULL) are skipped during aggregation.
Examples
Example 1: Basic usage with integer maps
Example 2: Group by aggregation
Example 3: NULL key and value handling
Example 4: NULL map handling
Usage notes
- Empty maps: Empty maps contribute nothing to the aggregation
- NULL maps: NULL map inputs (entire map is NULL) are skipped during aggregation
- NULL keys: Entries with NULL keys and non-NULL values are included and aggregated together under a single NULL key in the result
- NULL values: Entries with NULL values are excluded from the result, regardless of whether the key is NULL or not
- Key merging: Keys that appear in multiple maps have their values summed; keys that appear in only some maps are included with the sum of values from maps where they appear
- Supported types: The function only supports maps with numeric value types (TINYINT, SMALLINT, INT, BIGINT, LARGEINT, FLOAT, DOUBLE)
- Use cases: This function is particularly useful for aggregating counters, metrics, or any key-value data where values should be summed