【问题标题】:count categories of values计算值的类别
【发布时间】:2018-05-19 10:24:37
【问题描述】:

我在可空列中有intv >= 0,我想计算列中出现 Null、0、1 和 2+ 的次数如何有效地做到这一点?

【问题讨论】:

    标签: sql if-statement count distinct


    【解决方案1】:

    一种方法是group by:

    select (case when col in (0, 1) then cast(col as varchar(255))
                 else '2+'
            end) as grp, count(*)
    from t
    group by (case when col in (0, 1) then cast(col as varchar(255))
                   else '2+'
              end)
    order by min(col);
    

    cast() 的确切语法可能取决于数据库。这也假设所有值都是非负的。

    您也可以将计数放在不同的列中:

    select sum(case when val = 0 then 1 else 0 end) as cnt_0,
           sum(case when val = 1 then 1 else 0 end) as cnt_1,
           sum(case when val >= 2 then 1 else 0 end) as cnt_2pl
    from t;
    

    【讨论】:

    • sum(case when val is NULL then 1 else 0 end) as cnt_null 不见了
    猜你喜欢
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多