如何计算当前行与下一行?

How to calculate the current row with the next one?

在 Spark-Sql 1.6 版本中,使用 DataFrames,有没有办法针对特定列计算当前行和下一行的总和,对于每一行?

例如,如果我有一个只有一列的 table,就像这样

Age
12
23
31
67

我想要以下输出

Sum
35
54
98

最后一行被删除,因为没有要添加的 "next row"。

现在我正在通过对 table 进行排名并将其与自身合并来做到这一点,其中 rank 等于 rank+1

有更好的方法吗? 这可以用 Window 函数来完成吗?

是的,您绝对可以使用 rowsBetween 函数来处理 Window 函数。在下面的示例中,我将 person 列用于 grouping 目的。

import sqlContext.implicits._
import org.apache.spark.sql.functions._

val dataframe = Seq(
  ("A",12),
  ("A",23),
  ("A",31),
  ("A",67)
).toDF("person", "Age")

val windowSpec = Window.partitionBy("person").orderBy("Age").rowsBetween(0, 1)
val newDF = dataframe.withColumn("sum", sum(dataframe("Age")) over(windowSpec))
  newDF.filter(!(newDF("Age") === newDF("sum"))).show