powershell - 计算或查找特定键的唯一值
问题描述
我觉得这不应该那么难,但我很难记住一个数据结构,它会给我想要的东西。我有大量数据,我需要找到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
解决方案
使用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
}
}
推荐阅读
- android - 在android中通过网络发送消息
- php - 如何使用 PHP 从表单在同一项目中发送 PUT 请求
- javascript - this.value 和 $(this).val() 有什么区别?
- mysql - 如何创建存储过程并在预定时间运行它(在 MYSQL 中)
- javascript - 为什么 Edge 中的 sessionStorage 与 Firefox/Chrome 不同,我该如何更改?
- python - 字典中字符串值的总和
- c - redis中run_with_period c宏背后的确切语法或规范是什么
- javascript - 比较日期时间与当前日期时间
- javascript - 将字符串转换为标准矩格式
- android - 用户不选择图像时出现错误如何解决