我正在尝试将 SQL Group By & SUM 逻辑实现到 Scala 函数中。
我有一个对象列表,
case class TypeToSum(id: Int, active_total: Int, inactive_total: Int)
我正在通过合并多个列表来填充列表。最后,列表看起来像:
{id: 1, active_total: 4, inactive_total: 3},
{id: 1, active_total: 2, inactive_total: 5},
{id: 1, active_total: 1, inactive_total: 1},
{id: 2, active_total: 2, inactive_total: 7},
{id: 2, active_total: 6, inactive_total: 2}
我的目标是达到以下结果:
{id: 1, active_total: 7, inactive_total: 9},
{id: 2, active_total: 8, inactive_total: 9}
基本上我需要在按 id 分组时获得这些列的总和。在另一个函数中,我需要对一列求和,我可以使用以下代码来完成:
lossTotals.groupBy(totals => (totals.product_id, totals.part_id))
.mapValues(_.map(_.loss_sum).sum).map( .... )
如何实现这种方法(或另一种方法)以在同一列表中的不同字段上获得多个求和运算?
你可以这样做:
case class TypeToSum(id: Int, active_total: Int, inactive_total: Int) {
def merge(other: TypeToSum) = TypeToSum(id, active_total + other.active_total, inactive_total + other.inactive_total)
}
val ls = List(
TypeToSum(id = 1, active_total = 4, inactive_total = 3),
TypeToSum(id = 1, active_total = 2, inactive_total = 5),
TypeToSum(id = 1, active_total = 1, inactive_total = 1),
TypeToSum(id = 2, active_total = 2, inactive_total = 7),
TypeToSum(id = 2, active_total = 6, inactive_total = 2))
val sum = ls
.groupBy(_.id)
.mapValues {
case Nil => None
case List(x) => Some(x)
case ls => Some(ls.tail.foldLeft(ls.head)(_ merge _))
}
.values.flatten
println(sum)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句