case when 条件 then value_a else value_b end该语句表示:当条件成立时,值为value_a,不成立时值取value_b。
比如:你有一批渠道号,你想要得到这些渠道号是否属于top50,结果展示方式为“true”和“false”。
结果展示为这样:
查询语句:select channel_source,
case when channel_source in ('1006186q','1006186r','1009306c','1010184l','1010184m','1010680b','1010680m','1011512a','1011512c','1012046j','1012271f','1012271l','1012490o','1012644c','1015530g','1015530k','1015530l','1015530m','1017549g','1017549h','1017549k','1017549l','1017549v','1018357s','1018357t','1018682n','1018682o','1018682q','1019468p','1019468q','1019468r','1020184a','1020276a','1020539a','1020539b','1020539g','1020539h','1020539i','1020539j','1020539k','1020539l','1020539m','1020539n','1020539o','1020539q','1020539r','1020539s','1020539u','1020539v','1020539w','1000529c','1020539y','1000575g','1020896a','1000561u','1020896d','1020896e','1020896f','1020896g','1020896p','1020896q') then 'true' else 'false' end as top50
--如果channel_source在list(list为top50的渠道号汇总)里面,说明是top50,则返回true,否则返回false
from dw_msite_alad_highdown_channel ;
比如:你有一批用户,他们的资产水平各不相同,你想要对用户进行划分:资产<5000,为普通用户;5000=<资产<50000,为潜力用户;50000=<资产<500000,为高级用户;500000=<资产,为私用银行用户。
结果展示:
查询语句: select id ,total_asset,
case when total_asset <5000 then '普通用户'
when total_asset < 50000 then '潜力用户'
when total_asset < 500000 then '高端用户'
else '私用银行用户'
end as type --重新命名为type
from xiaofeishuiping;
比如:想对不同地区的销售额进行求和。
结果展示:
查询语句: select sum(case when city='b' then price else 0 end) as b_sum, --当city='b'时为price,否则为0,最后求和并且命名为b_sum。
sum(case when city='c' then price else 0 end) as c_sum,
sum(case when city='d' then price else 0 end) as d_sum
from huizongshuju;
比如:手里有个list( 'ucbrowser', 'baidubox', 'weixin', 'mqqbrowser', 'sogousearch')——各大浏览器按次序排的,
sql里需要匹配的字段长这个样子: