首页 > 解决方案 > 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 语句应该是什么样子的?

亲切的问候,

拉扎诺娃

标签: sqlcountcase

解决方案


使用两个级别的聚合。您可以使用窗口函数获得总数:

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;

推荐阅读