总和列计数两个不同的值

时间:2013-08-05 22:31:02

标签: mysql

我有一个可以容纳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

但是我想要将1和As,以及2和B这样的总和相加

mycol total
var1    51
var2    57
var3    12

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

1 个答案:

答案 0 :(得分: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);