Search code examples
neo4jcypher

Neo4j Cypher return multiple counts from a single query


For analytical purpose, I need to return multiple counts from a single query.

For example, I have a User entity. User has active property true/false.

Is it possible with Cypher to write a single query which will return a total number of all users, and also 2 additional count for active and inactive users? If so, please show how.


Solution

  • Here is the counts of active and inactive users. It is similar to SQL wherein it uses the sum() function and conditional clause "case when".

    MATCH (n:Person) 
    RETURN count(n) as user_counts, 
          sum(case when n.active then 1 end) as active, 
          sum(case when not n.active then 1 end) as inactive,
          sum(case when n.active is NULL then 1 end) as no_info
    

    Sample result using Persons nodes in movie database

    ╒═════════════╤════════╤══════════╤═════════╕
    │"user_counts"│"active"│"inactive"│"no_info"│
    ╞═════════════╪════════╪══════════╪═════════╡
    │133          │121     │7         │5        │
    └─────────────┴────────┴──────────┴─────────┘