我有一个数组,就像这样:
$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
我想按表获得Col1
和Col2
的总和:
Table Col1 Col2 ----- ----- ----- Table1 4 9 Table2 6 11
在SQL中,这将是:
SELECT Table, Col1 = SUM(Col1), Col2 = SUM(Col2)
FROM <$array>
GROUP BY Table
但是我不知道如何在PoSh中做到这一点。当然这应该相对简单吗?
答案 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
}
}