5.6 Using Aggregate Functions in SQL Graph Queries
You can use aggregate functions in a SQL graph query to obtain an aggregated output.
Both SQL built-in Aggregate Functions and user-defined aggregates are supported. These functions can be included in both fixed length and variable length path patterns in a SQL graph query.
The aggregate functions can be applied in the COLUMNS
clause
or in the graph pattern WHERE
clause of the SQL graph query. For
instance, consider the following sample query:
SELECT *
FROM GRAPH_TABLE ( g
MATCH (v1) (-[e]->(v2)){1,2}
COLUMNS (LISTAGG(v2.id, ',') AS id_list)
)
The preceding graph query describes a variable length path pattern having
{1,2}
as the quantifier. The LISTAGG
aggregate
function is used in the COLUMNS
clause to list all the
id
s along a path.
Similarly, you can also apply aggregations in a fixed length path pattern as shown:
SELECT *
FROM GRAPH_TABLE ( g
MATCH (v1) (-[e]->(v2)){2}
WHERE AVG(v2.age) >= 30
COLUMNS (LISTAGG(v2.id, ',') AS id_list)
)
The preceding graph query describes a fixed length path pattern. The
AVG
aggregate used in the WHERE
clause determines
only those paths where the average age >= 30
condition is met. The
resulting query output is a list of id
s along a path.
See Example 5-15 for example queries using aggregations.
Using binding_count() in SQL Graph Queries
You can use the binding_count()
aggregate to count the
number of bindings to an element variable. This aggregate can only be used inside
the COLUMNS
clause or in the graph pattern WHERE
clause of the SQL graph query. Also, note that you cannot specify
UNIQUE
or DISTINCT
on the
binding_count()
element variable.
For instance, consider the following sample query:
SELECT *
FROM GRAPH_TABLE ( g
MATCH (v1) (-[e]->(v2)){1,2}
COLUMNS (binding_count(v2) AS cnt, LISTAGG(v2.id, ',') AS id_list)
)
The preceding graph query outputs a list of id
s along a
path together with the count of bindings to v2
.
Also, see the Using binding_count() Aggregate example in Example 5-15.
Parent topic: SQL Graph Queries