跳转至

count函数

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

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

语法

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

示例

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 $$.player.name AS Name \
        | GROUP BY $-.Name YIELD $-.Name, count(*);
+---------------------+----------+
| $-.Name             | COUNT(*) |
+---------------------+----------+
| "Dejounte Murray"   | 1        |
+---------------------+----------+
| "LaMarcus Aldridge" | 2        |
+---------------------+----------+
| "Tim Duncan"        | 2        |
+---------------------+----------+
| "Marco Belinelli"   | 1        |
+---------------------+----------+
| "Manu Ginobili"     | 1        |
+---------------------+----------+
| "Boris Diaw"        | 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                   |
+------------+---------------------+

最后更新: 2021年5月14日