如果我要在 spark scala 中这样做,我会使用列名并定义如下聚合函数:
val df = List(("a", 1,2,3), ("a", 4,4,4)).toDF("id", "a", "b", "c")
// Note: df.columns.tail returns Array(a, b, c)
val aggs = df.columns.tail.map(_ -> "sum").toMap
//aggs: scala.collection.immutable.Map[String,String] = Map(a -> sum, b -> sum, c -> sum)
// Group by and execute aggregates:
df.groupBy($"id").agg(aggs).show
+---+------+------+------+
| id|sum(a)|sum(b)|sum(c)|
+---+------+------+------+
| a| 5| 6| 7|
+---+------+------+------+
另一种选择是在所有指定的列名称上运行相同的sum:
df.groupBy($"id").sum(df.columns.tail: _*).show() // to python users, :_* is a scala operator used to expand a list into a vararg
注意:您可能对此文档感兴趣:
https://spark.apache.org/docs/latest/api/scala/#org.apache.spark.sql.RelationalGroupedDataset