【发布时间】:2019-02-15 14:49:53
【问题描述】:
我想按月比较 Prev.data 和 Current 数据。我有如下数据。
Data-set 1 : (Prev) Data-set 2 : (Latest)
Year-month Sum-count Year-Month Sum-count
-- -- 201808 48
201807 30 201807 22
201806 20 201806 20
201805 35 201805 20
201804 12 201804 9
201803 15 -- --
我有如上所示的数据集。我想根据年月列和总和来比较这两个数据集,并且需要找出百分比的差异。
我正在使用 spark 2.3.0 和 Scala 2.11。
这里是模式:
import org.apache.spark.sql.functions.lag
val mdf = spark.read.format("csv").
option("InferSchema","true").
option("header","true").
option("delimiter",",").
option("charset","utf-8").
load("c:\\test.csv")
mdf.createOrReplaceTempView("test")
val res= spark.sql("select year-month,SUM(Sum-count) as SUM_AMT from test d group by year-month")
val win = org.apache.spark.sql.expressions.Window.orderBy("data_ym")
val res1 = res.withColumn("Prev_month", lag("SUM_AMT", 1,0).over(win)).withColumn("percentage",col("Prev_month") / sum("SUM_AMT").over()).show()
我需要这样的输出:
如果百分比超过 10%,那么我需要将标志设置为 F。
set1 cnt set2 cnt output(Percentage) Flag
201807 30 201807 22 7% T
201806 20 201806 20 0% T
201805 35 201805 20 57% F
请帮帮我。
【问题讨论】:
-
你能添加一个想要输出的例子吗?谢谢
-
您好,我已经更新了我的查询。非常感谢。
-
你是如何计算百分比的?输出中指定的值是否正确?