window 函数中包含当前日期的自定义月份范围
Custom month range with current date in window function
我正在尝试找出一种方法,将日期列上的 window 分区与今天的日期进行比较来使用每月范围。
所以假设今天是 2021 年 1 月 21 日,所以我需要将月份和年份获取为 202101,然后根据推导出的值设置月份范围。
像 2 个月前的行,202101 = 202011
然后在获得的结果上我需要在另一列上使用聚合。
所以如果输入是:
Id,date, price
1,1-10-2021,5
1,1-11-2021,6
1,1-09-2021,10
当前日期是20 Jan 2021
所以如果我想要最近两个月(12 月和 11 月)的汇总,那么输出应该是 5
如果我想要最近三个月(12 月、11 月、10 月)的汇总,输出应该是 11
在这种情况下,您不需要 Window。只需按 id
分组并使用条件求和聚合:
from pyspark.sql import functions as F
df = spark.createDataFrame([
(1, "2021-10-01", 5), (1, "2021-11-01", 6),
(1, "2021-09-01", 10), (2, "2021-12-01", 9)
], ["Id", "date", "price"])
nb_last_months = 2
df1 = df.groupBy("id").agg(
F.sum(
F.when(
F.col("date") >= F.add_months(F.date_trunc("month", F.current_date()), - nb_last_months),
F.col("price")
)
).alias(f"sum_last_{nb_last_months}_months")
)
df1.show()
#+---+-----------------+
#| id|sum_last_2_months|
#+---+-----------------+
#| 1| 6|
#| 2| 9|
#+---+-----------------+
我正在尝试找出一种方法,将日期列上的 window 分区与今天的日期进行比较来使用每月范围。
所以假设今天是 2021 年 1 月 21 日,所以我需要将月份和年份获取为 202101,然后根据推导出的值设置月份范围。
像 2 个月前的行,202101 = 202011
然后在获得的结果上我需要在另一列上使用聚合。
所以如果输入是:
Id,date, price
1,1-10-2021,5
1,1-11-2021,6
1,1-09-2021,10
当前日期是20 Jan 2021
所以如果我想要最近两个月(12 月和 11 月)的汇总,那么输出应该是 5
如果我想要最近三个月(12 月、11 月、10 月)的汇总,输出应该是 11
在这种情况下,您不需要 Window。只需按 id
分组并使用条件求和聚合:
from pyspark.sql import functions as F
df = spark.createDataFrame([
(1, "2021-10-01", 5), (1, "2021-11-01", 6),
(1, "2021-09-01", 10), (2, "2021-12-01", 9)
], ["Id", "date", "price"])
nb_last_months = 2
df1 = df.groupBy("id").agg(
F.sum(
F.when(
F.col("date") >= F.add_months(F.date_trunc("month", F.current_date()), - nb_last_months),
F.col("price")
)
).alias(f"sum_last_{nb_last_months}_months")
)
df1.show()
#+---+-----------------+
#| id|sum_last_2_months|
#+---+-----------------+
#| 1| 6|
#| 2| 9|
#+---+-----------------+