- Categories:
Aggregate functions (Semi-structured Data) , Window functions (General) , Semi-structured and structured data functions (Array/Object)
OBJECT_ AGG¶
Returns one OBJECT per group. For each (key, value) input pair, where key
must be a VARCHAR and value must be a VARIANT, the resulting OBJECT contains
a key:value field.
- Aliases:
OBJECTAGG
Syntax¶
Aggregate function
Window function
Usage notes¶
- Input tuples with NULL
keyand/orvalueare ignored. - Duplicate keys within a group result in a
Duplicate field key 'key'error. - The DISTINCT keyword is supported, but it only filters out duplicate
rows where both
keyandvalueare equal.
- When this function is called as a window function, it does not support:
- An ORDER BY clause within the OVER clause.
- Explicit window frames.
Examples¶
These examples build a table of key-value pairs, then use OBJECT_AGG to collect the pairs in each group into a single OBJECT (for example, gathering a person’s attributes into one object per person).
First, create and populate a table. The value column is typed as VARIANT because the
value argument of OBJECT_AGG must be a VARIANT, so each inserted value is
cast with ::VARIANT:
This example uses OBJECT_AGG as an aggregate function. Grouping by g produces one OBJECT per group,
where each k value becomes a key and its v value becomes the corresponding value:
The following example is optional and shows how to expand the aggregated objects back into rows. It passes the OBJECT produced by OBJECT_AGG to FLATTEN, which returns one row for each key-value pair in each object: