什么时候使用case?case的作用?
比如现在的需求是查询一张表中,ID为0~20标记为TOP,ID为21~30标记为Center,ID为其他值则标记为Other,设置标记字段为type,则使用case的查询方法:
select id,
case
when id > 0 and id <= 20 then 'TOP'
when id >20 and id <= 30 then 'Center'
else 'Other'
end as type
from taskConfig
查询的结果:
case等于是增加查询结果集的一个字段,这个字段的值是可控制的。下面是增加group by 和having的结合使用
select mainversion,
case
when positionid=1 and itemid=44 then 1
when positionid=93 and itemid=2 then 93
else 0
end as source
from GameCenterLogs_20160106
where
mainversion is not null
group by source
having source > 0;
查询的结果:
可以说case增加的字段和普通查询的字段没什么区别,可以灵活使用。