1

我有一列可以容纳 6 个值(1、2、3、A、B、C)

我可以数(*)它们,所以它看起来像这样

select mycol, count(*) as ttl from mytable group by mycol;
    mycol  ttl
    1       46
    2       53
    3       10
    A       5 
    B       4
    C       2

但我想像这样总结 1s 和 As,以及 2s 和 Bs

mycol total
var1    51
var2    57
var3    12

案例陈述会为此工作吗?像案例 1 或 A 一样对待它们

4

1 回答 1

3

是的,一个case声明将为此工作:

select (case when mycol in ('1', 'var1') then 'var1'
             when mycol in ('2', 'var2') then 'var2'
             when mycol in ('3', 'var3') then 'var3'
        end),
       sum(ttl) as Total
from mytable t
group by (case when mycol in ('1', 'var1') then 'var1'
               when mycol in ('2', 'var2') then 'var2'
               when mycol in ('3', 'var3') then 'var3'
          end);

编辑:

如果您只有每个值包含多行的数据:

select (case when mycol in ('1', 'var1') then 'var1'
             when mycol in ('2', 'var2') then 'var2'
             when mycol in ('3', 'var3') then 'var3'
        end),
       count(*) as Total
from mytable t
group by (case when mycol in ('1', 'var1') then 'var1'
               when mycol in ('2', 'var2') then 'var2'
               when mycol in ('3', 'var3') then 'var3'
          end);
于 2013-08-05T22:36:41.400 回答