跳转至

count函数Graph

count()函数可以计数指定的值或行数。

  • (原生nGQL)用户可以同时使用count()GROUP BY对指定的值进行分组和计数,再使用YIELD返回结果。
  • (openCypher方式)用户可以使用count()对指定的值进行计数,再使用RETURN返回结果。不需要使用GROUP BY

语法Graph

count({expr | *})
  • count(*)返回总行数(包括NULL)。
  • count(expr)返回满足表达式的非空值的总数。
  • count()size()是不同的。

示例Graph

nebula> WITH [NULL, 1, 1, 2, 2] As a UNWIND a AS b \
        RETURN count(b), count(*), count(DISTINCT b);
+----------+----------+-------------------+
| count(b) | count(*) | count(distinct b) |
+----------+----------+-------------------+
| 4        | 5        | 2                 |
+----------+----------+-------------------+
# 返回player101 follow的人,以及follow player101的人,即双向查询。
nebula> GO FROM "player101" OVER follow BIDIRECT \
        YIELD properties($$).name AS Name \
        | GROUP BY $-.Name YIELD $-.Name, count(*);
+---------------------+----------+
| $-.Name             | count(*) |
+---------------------+----------+
| "LaMarcus Aldridge" | 2        |
| "Tim Duncan"        | 2        |
| "Marco Belinelli"   | 1        |
| "Manu Ginobili"     | 1        |
| "Boris Diaw"        | 1        |
| "Dejounte Murray"   | 1        |
+---------------------+----------+

上述示例的返回结果有两列:

  • $-.Name:查询结果包含的姓名。
  • count(*):姓名出现的次数。

因为测试数据集basketballplayer中没有重复的姓名,count(*)列中数字2表示该行的人和player101是互相follow的关系。

# 方法一:统计数据库中的年龄分布情况。
nebula> LOOKUP ON player \
        YIELD player.age As playerage \
        | GROUP BY $-.playerage \
        YIELD $-.playerage as age, count(*) AS number \
        | ORDER BY $-.number DESC, $-.age DESC;
+-----+--------+
| age | number |
+-----+--------+
| 34  | 4      |
| 33  | 4      |
| 30  | 4      |
| 29  | 4      |
| 38  | 3      |
+-----+--------+
...

# 方法二:统计数据库中的年龄分布情况。
nebula> MATCH (n:player) \
        RETURN n.age as age, count(*) as number \
        ORDER BY number DESC, age DESC;
+-----+--------+
| age | number |
+-----+--------+
| 34  | 4      |
| 33  | 4      |
| 30  | 4      |
| 29  | 4      |
| 38  | 3      |
+-----+--------+
...
# 统计Tim Duncan关联的边数。
nebula> MATCH (v:player{name:"Tim Duncan"}) -- (v2) \
        RETURN count(DISTINCT v2);
+--------------------+
| count(distinct v2) |
+--------------------+
| 11                 |
+--------------------+

# 多跳查询,统计Tim Duncan关联的边数,返回两列(不去重和去重)。
nebula> MATCH (n:player {name : "Tim Duncan"})-[]->(friend:player)-[]->(fof:player) \
        RETURN count(fof), count(DISTINCT fof);
+------------+---------------------+
| count(fof) | count(distinct fof) |
+------------+---------------------+
| 4          | 3                   |
+------------+---------------------+

最后更新: November 1, 2021
Back to top