joh*_*und 2 scala aggregate-functions apache-spark apache-spark-sql
我想使用列名数组作为输入聚合Spark数据框,同时保留列的原始名称.
df.groupBy($"id").sum(colNames:_*)
Run Code Online (Sandbox Code Playgroud)
这有效,但无法保留名称.受到这里找到的答案的启发,我没有尝试过这个:
df.groupBy($"id").agg(sum(colNames:_*).alias(colNames:_*))
error: no `: _*' annotation allowed here
Run Code Online (Sandbox Code Playgroud)
它可以像单个元素一样
df.groupBy($"id").agg(sum(colNames(2)).alias(colNames(2)))
Run Code Online (Sandbox Code Playgroud)
如何才能使整个阵列发生这种情况?
只需提供带别名的列序列:
val colNames: Seq[String] = ???
val exprs = colNames.map(c => sum(c).alias(c))
df.groupBy($"id").agg(exprs.head, exprs.tail: _*)
Run Code Online (Sandbox Code Playgroud)