如何对按数组中onother属性分组的属性进行汇总?

时间:2019-07-09 18:34:42

标签: arrays powershell grouping

我有一个数组,就像这样:

$array = @()
$Props = [ordered]@{Table="Table1"; Col1=1; Col2=2}
$array += New-Object psobject -Property $Props
$Props = [ordered]@{Table="Table2"; Col1=4; Col2=5}
$array += New-Object psobject -Property $Props
$Props = [ordered]@{Table="Table1"; Col1=3; Col2=7}
$array += New-Object psobject -Property $Props
$Props = [ordered]@{Table="Table2"; Col1=2; Col2=6}
$array += New-Object psobject -Property $Props

我想按表获得Col1Col2的总和:

Table    Col1    Col2
-----    -----   -----
Table1       4       9
Table2       6      11

在SQL中,这将是:

SELECT Table, Col1 = SUM(Col1), Col2 = SUM(Col2)
FROM <$array>
GROUP BY Table

但是我不知道如何在PoSh中做到这一点。当然这应该相对简单吗?

1 个答案:

答案 0 :(得分:2)

翻转SQL语句的头,您基本上就知道在PowerShell中要执行的操作-按表名分组,然后选择每个表的总和!

# Group the objects by table name
$Tables = $array |Group Table

# Select the table name + sum of each group
$Tables |Select-Object Name,@{Name='Sum1';Expression={($_.Group |Measure-Object Col1 -Sum).Sum}},@{Name='Sum2';Expression={($_.Group |Measure-Object Col2 -Sum).Sum}}

Select-Object的最后两个参数是计算表达式:

@{
  # Select a new property named "Sum1"
  Name = 'Sum1'
  Expression = {
    # Calculate the value from the sum of the Col1 properties in this table
    ($_.Group |Measure-Object Col1 -Sum).Sum
  }
}