Powershell 按多个属性分组 [英] Powershell Group By Multiple Properties
本文介绍了Powershell 按多个属性分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试确定是否有一种更简单的方法来编写一个 Powershell 函数,该函数将数组按多个属性分组并对组中的指定属性求和,类似于以下内容:
I am trying to determine if there's an easier way to write a Powershell function that groups an array by multiple properties and sums specified properties in the group, similar to the following:
#Ungrouped data
ID ID2 Value
-- --- -----
A A1 100
A A2 200
A A2 300
B B1 400
B B1 500
B B1 600
B B3 700
C C1 800
C C2 900
C C1 1000
#Grouped data
ID ID2 Sum Value
-- --- ---------
A A1 100
A A2 500
B B1 1500
B B3 700
C C1 1800
C C2 900
这是我目前所拥有的:
$grouped = $ungrouped | group ID, ID2
$grouped | foreach {
[pscustomobject] @{
ID = $_.group | select -unique -expand ID
ID2 = $_.group | select -unique -expand ID2
'Sum Value' = ($_.group | measure value -sum).sum
}
}
这对我有用,但我只是觉得我做得太过分了,可能有一种更简洁的方式来写这个,特别是如果我按更多属性分组并且想要总结或聚合更多分组的值.
This works for me, but I just get the feeling I'm overdoing it and there may be a more concise way to write this, especially if I was grouping by more properties and wanted to sum up or aggregate more grouped values.
预先感谢您的帮助!
推荐答案
我也一样,也许简单一点,我去掉两个|
I have the same, perhaps a bit simpler, I remove two |
$grouped = $ungrouped | group ID, ID2
$grouped | foreach {
$b= $_.name -split ', '
[pscustomobject] @{
ID = $b[0];ID2 = $b[1]
'Sum Value' = ($_.group | measure value -sum).sum
}
}
一个班轮:
Import-Csv 'YourFile.csv' | Group-Object -Property ID,ID2 | % {$b=$_.name -split ', ';$c=($_.group | Measure-Object -Property value -Sum).Sum;[PScustomobject]@{ID=$b[0];ID2=$b[1];Sum=$c}}
这篇关于Powershell 按多个属性分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文