Apache Spark:查询成功率

问题描述 投票:0回答:2

我刚开始学习SQL和Apache Spark。

我在Spark中导入了一个SQL表。

现在我需要根据需要“是”的字段找到成功率。

所以我需要找到总行数除以具有特定字段为“是”的行数

我能够单独找到结果,但不知道如何组合这两个查询。

sqlContext.sql("select count(*) from customers") 

res51: org.apache.spark.sql.DataFrame = [_c0: bigint]

sqlContext.sql("select count(*) from customers where custSub = 'yes'")

res52: org.apache.spark.sql.DataFrame = [_c0: bigint]

我可以使用单个查询找出结果,还是在存储单个查询的结果后需要执行任何操作。

你能帮我解决这个问题吗?

sql scala apache-spark spark-dataframe
2个回答
0
投票

您可以使用条件聚合来执行此操作。

sqlContext.sql("""select count(case when custSub = 'yes' then 1 end)/count(*) 
                  from customers
               """)

0
投票

这是使用avg()获得费率的一个不错的小技巧:

select avg(case when custSub = 'yes' then 1.0 else 0.0 end) as rate
from customers;
© www.soinside.com 2019 - 2024. All rights reserved.