我有以下資料,
logType log_create_date error_date
A 2019-01-01 2019-01-02
A 2019-02-04 2019-02-03
A 2019-03-10 2019-03-07
A 2019-04-13 2019-04-08
B 2019-05-17 2019-05-10
B 2019-06-20 2019-06-11
B 2019-07-24 2019-07-13
B 2019-08-27 2019-08-14
我已經設法在下面使用,
val window = Window.orderBy("logType","log_crate_date")
val lagCol = lag(col("log_crate_date"), 1).over(window)
spark.sql("SELECT * FROM test")
.withColumn("log_create_date_previous", lagCol)
.select("logType","log_create_date_previous","log_create_date","error_date")
logType log_create_date_previous log_create_date error_date
A null 2019-01-01 2019-01-02
A 2019-01-01 2019-02-04 2019-02-03
A 2019-02-04 2019-03-10 2019-03-07
A 2019-03-10 2019-04-13 2019-04-08
B 2019-04-13 2019-05-17 2019-05-10
B 2019-05-17 2019-06-20 2019-06-11
B 2019-06-20 2019-07-24 2019-07-13
B 2019-07-24 2019-08-27 2019-08-14
B 2019-08-27 2019-08-27 null
現在我想計算每個 $logType,并且在 b/wa 中不同的 log_create_date_previous 和 log_create_date 通過計算有多少 error_date 落在 log_create_date_previous 和 log_create_date 下,發生了多少錯誤日期計數。
uj5u.com熱心網友回復:
為了計算每種型別的“log_create_date_previous”和“log_create_date”之間有多少條記錄有“error_date”,可以使用“between”函式:
.withColumn("error_in_between", $"error_date".between($"log_create_date_previous", $"log_create_date"))
.groupBy("logType").agg(sum(when($"error_in_between", 1).otherwise(0)).alias("error_count"))
對于提供的資料集,結果是:
------- -----------
|logType|error_count|
------- -----------
|A |3 |
|B |4 |
------- -----------
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/418187.html
標籤:
