【问题标题】:SQL: Checking value counts of a columnSQL:检查列的值计数
【发布时间】:2021-07-23 17:25:52
【问题描述】:

我想检查表中的列是否包含具有少量值计数的值。

以下表为例:

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]

通过上面的示例,我应该得到:“此字段的某些值具有少量值计数” 因为产品 G 不到产品总数的 5%。

SQL 语句应该是什么样子?

致以诚挚的问候,

拉扎诺瓦

【问题讨论】:

    标签: sql count case


    【解决方案1】:

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

    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;
    

    【讨论】:

    • 哇! :D 再次...感谢 Gordon 的快速回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-26
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多