【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

 

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