我有一列可以容纳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和Bs加起来
mycol total
var1 51
var2 57
var3 12
案例陈述对此有用吗?就像案例1或A一样,然后对他们一视同仁
最佳答案
是的,一个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);
关于mysql - 两个不同值的列总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18068886/