case when不仅仅用到在查找,我们还有一种运用:就是分类汇总
比如,我们有4类数据,如下表
id type value
---------------------------
1 1 1
2 1 1
3 2 1
4 3 1
5 2 1
6 4 1
7 3 1
8 1 1
select
sum(case when type=1 then value else 0) type1value,
sum(case when type=2 then value else 0) type2value,
sum(case when type=3 then value else 0) type3value,
sum(case when type=4 then value else 0) type4value,
sum(value) total
from table
result:
type1value type2value type3value type4value total
-----------------------------------------------------------------------------------
3 2 2 1 8
这种情况不好弄了吧? |