sql - SQL:检查列的值计数
问题描述
我想检查表中的列是否具有少量值计数的值。
以下表为例:
RowID |Product
1 | A
2 | A
3 | B
...
200.000 | C
下表汇总了上表:
Product |Count
A |204
B |682
C |553
D |1402
E |30855
F |357
G |1
H |542
我想知道我的表的 Product 列是,一个 Product 的计数是否小于 5%。如果是这样,SQL 语句应该返回:“该字段的某些值具有少量值计数”
换句话说: IF [MinValueCount]/[Count] <= .05 then '此字段的某些值具有少量值计数' else 'null'
通过上面的示例,我应该得到:“该字段的某些值的值计数很少”,因为产品 G 小于产品总数的 5%。
SQL 语句应该是什么样子的?
亲切的问候,
拉扎诺娃
解决方案
使用两个级别的聚合。您可以使用窗口函数获得总数:
select max( 'Some values of this field have a small number of value counts')
from (select product, count(*) as cnt,
sum(count(*)) over () as total_cnt
from t
) t
where cnt < 0.05 * total_cnt;
在外部查询中使用的max()
只是返回一行。您还可以使用fetch
或类似的子句(无论您的数据库支持什么):
select 'Some values of this field have a small number of value counts'
from (select product, count(*) as cnt,
sum(count(*)) over () as total_cnt
from t
) t
where cnt < 0.05 * total_cnt
fetch first 1 row only;
推荐阅读
- objective-c - 在 macOS 上,我遇到了问题。在我所有的非沙盒项目中运行 10.14.2,在任何 NSOpenPanel 中,右键单击命令都不起作用。任何想法?
- python - 如何修复 AWS lambda 中的“无法导入模块”错误
- angular - 在来自 http GET、Angular 6 的输入字段中显示对象
- sql - 如何禁用特定 Pervasive 用户帐户的存储过程查看权限?
- c# - 如何在 swagger 中修改关联数组、哈希或字典中的键以获取文档?
- python - 将查询参数添加到 URL
- python - 递增增加列表中的非零元素
- python - 使用 PIL 使文本大小自动调整为图像
- sql-server - SQL Server:不同表中列之间的关系
- javascript - 多次更改段落以匹配幻灯片中更改的图像