【SQL学习笔记4】case when 和if的用法

1.case用法

-- 用法一:
case when 条件1 then 字段取值1
when 条件2 then 字段取值2
when 条件3 then 字段取值3
else 字段取值4-- 如果上述全部不满足,则执行
end

-- 用法二:
case 字段名
when 取值1 then 字段取值1
when 取值2 then 字段取值2
when 取值3 then 字段取值3
else 字段取值4-- 如果上述全部不满足,则执行
end

2.if用法

if(条件,取值1,取值2)--若条件满足,则取值1,否则取值2

例子:现有用户行为数据表etl_online,查找2020年12月1日-2020年12月15日文章的下发数量,下发未曝光数量,曝光未点击数量,点击数量:

create table etl_online(
user_id varchar(20),-- 用户id
doc_id varchar(20),-- 文章id
auction varchar(20),-- 用户行为
p_day varchar(20)-- 时间
)
select p_day,doc_id,
case when click>0 then '点击'
when click<0 and rview>0 then '曝光未点击'
when rview<0 and vview>0 then '下发未点击'
when view<0 then '未下发'
else '其他' end as user_action,
count(user_id) as usrnum
(select p_day,doc_id,user_id, sum(click) as click, sum(view) as vview, sum(review) as rview
from
(select p_day,doc_id,user_id
if (uaction ='CLICK',1,0) as click,
if(uaction='VIEW',1,0) as vview,
if(uaction='RVIEW',1,0) as rview
from eta_online
where p_day between '2020-12-01' and '2020-12-15'
group by 1,2,3,4,5,6) as a
group by 1,2,3
) as a
group by 1,2,3

再来一个例子:

查询语文成绩优秀(85以上),良好(70-85),及格(60-70)的人数:

grade表的数据结构详见:https://blog.csdn.net/Icesj0280/article/details/111546189

方法一:

select GP,count(GP) as num from
(select stu_id,
case when grade>=85 then'优秀'
when grade>=70 and grade <85 then '良好'
when grade<70 and grade >=60 then '及格'
else '不及格' end as GP
from
grade
join
(select couid from course where couname='语文') as a
on a.couid=grade.couid)
group by 1

方法二:

select count(if(grade>=85,stu_id,null)) as A,
count(if(grade>=70 and grade<85,stu_id,null)) as B,
count(if(grade>=60 and grade<70,stu_id,null)) as C,
count(if(grade<60,stu_id,null)) as D
from grade 
join
(select couid from course where couname='语文') as a
on grade.stu_id=a.stu_id

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章