【问题标题】:How to group_by and calculate percentage using Cypher queries in Neo4j如何在 Neo4j 中使用 Cypher 查询进行分组和计算百分比
【发布时间】:2016-06-19 00:12:55
【问题描述】:

我在图形数据库中创建了 3 个节点,始发机场和目的地机场以及承运人。它们通过名为“canceled_by”的属性相关联。

   MATCH (origin:origin_airport {name: row.ORIGIN}),
   (destination:dest_airport {name: row.DEST}),
   (carrier:Carrier {name: row.UNIQUE_CARRIER})
   CREATE (origin)-[:cancelled_by {cancellation: row.count}]->(carrier)
   CREATE (origin)-[:cancelled_by {cancellation: row.count}]->(destination)
   CREATE (origin)-[:operated_by {carrier: row.UNIQUE_CARRIER}]->(carrier)

cancelled_by 保存特定运营商被取消的次数。我的输入文件将采用以下格式:

ORIGIN  UNIQUE_CARRIER  DEST    Cancelled
 ABE    DL                ATL    1
 ABE    EV                ATL    1
 ABE    EV                DTW    3
 ABE    EV                ORD    3
 ABQ    DL                DFW    2
 ABQ    B6                JFK    2

这里我需要计算每个运营商的取消百分比。我期待的结果如下:

UNIQUE_CARRIER  DEST    Percentage_Cancelled
    DL                   25%
    EV                   58.33%
    B6                   16.66%

Example: Total number of cancellation = 12
No of cancellation for DL = 3
Percentage of cancellation for DL = (3/12)*100 = 25%

以下查询给出了每个承运人的取消总和:

 MATCH ()-[ca:cancelled_by]->(c:Carrier)
 RETURN c.name  AS Carrier, 
 SUM(toFloat(ca.cancellation)) As sum
 ORDER BY sum DESC
 LIMIT 10

我尝试了以下查询来计算百分比:

  MATCH ()-[ca:cancelled_by]->(c:Carrier)
  WITH SUM(toFloat(ca.cancellation)) As total
  MATCH ()-[ca:cancelled_by]->(c:Carrier)
  RETURN c.name  AS Carrier, 
  (toFloat(ca.cancellation)/total)*100 AS percent
  ORDER BY percent DESC
  LIMIT 10

但它不是通过分组计算百分比,而是单独计算百分比。

     Carrier    sum
        DL    0.36862408915559364
        DL    0.34290612944706383
        DL    0.3171881697385341

如何在 Neo4j 中使用 cypher 查询基于 group_by 计算百分比?

【问题讨论】:

  • 是的。将注册。与此同时,我自己尝试了一些查询来习惯它。您对上述问题有什么建议吗?

标签: r neo4j cypher


【解决方案1】:

您在分组时忘记了每个载波的总和,并且不一定总是使用强制转换来浮动 - 只是在最后一次计算乘以浮点数时。

MATCH ()-[ca:cancelled_by]->(:Carrier)
  WITH SUM(ca.cancellation) As total
  MATCH ()-[ca:cancelled_by]->(c:Carrier)
RETURN c.name AS Carrier, 
       100.0 * SUM(ca.cancellation) / total AS percent
  ORDER BY percent DESC
  LIMIT 10

【讨论】:

    【解决方案2】:

    您好,您可以尝试使用 R dplyr 包。 将链接操作%>% 与函数一起使用 group_bysummarizetransmutegroup_bysummarize 会给你每组内取消的总和。使用 transmute 函数获取相对频率。

    【讨论】:

    • 我在 Neo4j 中使用密码查询来尝试这个
    • 对不起。我看到了 R 标签,想到了一个 R 解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 2020-07-31
    • 2011-09-06
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多