Import-CSV GroupBy Sum

爷,独闯天下 提交于 2020-01-04 02:38:11

问题


I am stuck trying to get meaningful output from a csv file.

The raw input looks like this.

Col1,Col2,Col3,Col4
a,2,b,z
a,2,c,x
a,1,d,y
e,1,f,s
e,2,g,t
h,1,k,r

I am trying to achieve an output of below (exclude col4) and export to a file for further reporting using PowerShell 2.

a  5  b,c,d
e  3  f,g
h  1  k

Code from my script function is:

    $data = import-csv $filename.csv | Select-Object -property Col1,Col2,Col3 
    $view | Group Col1 | `
    select Name,@{  
      Name="Col2Sum"; 
       Expression = {  
         [math]::round(($_.Group | Measure-Object -Sum Col2).Sum/60,2) 
       } 
      } | `
    Sort "Col2Sum" -desc | ft -auto -GroupBy Col | out-file $file.txt

Where I am stuck is how to produce arrays from Col3 in one line and output them properly.

If anyone has any ideas.


回答1:


Can you try this :

    $a = import-csv C:\temp\F.csv |Group-Object -Property col1 | `
         % {$_.name + " "  + $_.count + " " + `
         ($_.group | % {$i=0;$j=$_.count}{$i++ ; $_.col3 + ","*($j-$i -gt 0)})}
    $a

a 3 b, c, d
e 2 f, g
h 1 k

And then

    $a = import-csv C:\temp\F.csv |Group-Object -Property col1 | `
         % {$_.name + " "  + ($_.group | %{$i=0}{$i+=$_.col2}{$i}) + " " + `
         ($_.group | % {$i=0;$j=$_.count}{$i++ ; $_.col3 + ","*($j-$i -gt 0)})}
    $a

a 5 b, c, d
e 3 f, g
h 1 k


来源:https://stackoverflow.com/questions/13050408/import-csv-groupby-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!