首页 > 解决方案 > 计算或查找特定键的唯一值

问题描述

我觉得这不应该那么难,但我很难记住一个数据结构,它会给我想要的东西。我有大量数据,我需要找到Secondary Identifiers下面定义的多个实例。

Primary Identifier,Secondary Identifier,Fruit
11111,1,apple
11111,1,pear
22222,1,banana
22222,1,grapefruit
33333,1,apple
33333,1,pear
33333,2,apple
33333,2,orange

这可能不是一个很好的例子——但基本上只有两列很重要。我真正想要的是返回Primary Identifiers唯一计数Secondary Identifiers大于 1 的地方。所以我想也许 aHashTable是我最好的选择,但我试图以面向管道的方式做某事但失败了,所以我想知道是否有更简单的方法或者Cmdlet我没有尝试过。

最后的array(或hashtable)将是这样的:

ID      Count of Secondary ID
-----   ---------------------
11111   1
22222   1
33333   2

那时,获取多个实例就像$array | Where-Object {$_."Count of Secondary ID" -gt 1}

如果这个例子很糟糕或者我所追求的没有意义,请告诉我,我可以重写它;但这几乎就像我需要一个Select-Object -Unique允许您使用两个或多个输入对象/列的实现。基本上与Excel删除重复项然后选择要包含的标题相同。除了有太多行无法打开Excel

标签: powershell

解决方案


使用Group-Object两次 - 首先按 common 对对象进行分组Primary Identifier,然后再次使用来计算每组Group-Object中 distinct 的数量:Secondary Identifier

$data = @'
Primary Identifier,Secondary Identifier,Fruit
11111,1,apple
11111,1,pear
22222,1,banana
22222,1,grapefruit
33333,1,apple
33333,1,pear
33333,2,apple
33333,2,orange
'@ |ConvertFrom-Csv 

$data |Group-Object 'Primary Identifier' |ForEach-Object {
  [pscustomobject]@{
    # Primary Identifier value will be the name of the group, since that's what we grouped by
    'Primary Identifier' = $_.Name
    # Use `Group-Object -NoElement` to count unique values - you could also use `Sort-Object -Unique`
    'Count of distinct Secondary Identifiers' = @($_.Group |Group-Object 'Secondary Identifier' -NoElement).Count
  }
}

推荐阅读