【发布时间】:2020-03-11 09:25:05
【问题描述】:
我是 SparkSQL 的新手,我想计算我的数据中每种状态的百分比。 这是我的数据,如下所示:
A B
11 1
11 3
12 1
13 3
12 2
13 1
11 1
12 2
所以,我可以这样在 SQL 中做到这一点:
select (C.oneTotal / C.total) as onePercentage,
(C.twoTotal / C.total) as twotPercentage,
(C.threeTotal / C.total) as threPercentage
from (select count(*) as total,
A,
sum(case when B = '1' then 1 else 0 end) as oneTotal,
sum(case when B = '2' then 1 else 0 end) as twoTotal,
sum(case when B = '3' then 1 else 0 end) as threeTotal
from test
group by A) as C;
但在 SparkSQL DataFrame 中,我首先计算每个状态的 totalCount,如下所示:
// wrong code
val cc = transDF.select("transData.*").groupBy("A")
.agg(count("transData.*").alias("total"),
sum(when(col("B") === "1", 1)).otherwise(0)).alias("oneTotal")
sum(when(col("B") === "2", 1).otherwise(0)).alias("twoTotal")
我用错了吗? 如何像我上面的 SQL 一样在 SparkSQL 中实现它?然后计算每个状态的占比?
感谢您的帮助。最后,我用 sum(when) 解决它。以下是我当前的代码。
val cc = transDF.select("transData.*").groupBy("A")
.agg(count("transData.*").alias("total"),
sum(when(col("B") === "1", 1).otherwise(0)).alias("oneTotal"),
sum(when(col("B") === "2", 1).otherwise(0)).alias("twoTotal"))
.select(col("total"),
col("A"),
col("oneTotal") / col("total").alias("oneRate"),
col("twoTotal") / col("total").alias("twoRate"))
再次感谢。
【问题讨论】:
-
欢迎来到 SO。请不要在图片中发布代码,请将其添加到您的帖子中。
-
你检查
A是1还是2,你需要检查colB,即sum(when(col("B")==="1") -
@Andrew 很抱歉,我改了。
标签: scala apache-spark apache-spark-sql