CASE WHEN

工作中常用sql语句:https://mp.weixin.qq.com/s/G71VhGLoM6rwUGah5PaZhQ
sql常见面试题:
https://www.bilibili.com/read/cv8481239/

case when用法
select case 字段 when 1 then ‘有’ else ‘无’ end as 字段 from 表
select (case when password is null then ‘1’ else password ) end ) as 字段 from 表

select
t3.region_id as ‘regionId’,
t3.region_name as ‘regionName’,
count(case when t1.tricolor = 1 then 1 else null end ) as ‘greenTotal’,
count(case when t1.tricolor = 2 then 1 else null end ) as ‘yellowTotal’,
count(case when t1.tricolor = 3 then 1 else null end )as ‘redTotal’
from pa_household_member t1
left join pa_household t2 on t2.household_id = t1.household_id
left join system_region t3 on t3.region_id = t2.area
group by t2.area

select d.tools_name, null as sum,null as num,dtp.specs,dtp.type,count( case when state =0 then ‘state’ end ) as 在库 ,
count(case when state =1 then ‘state’ end) 借出 ,
count(case when state =2 then ‘state’ end) 丢失,
count(case when state =3 then ‘state’ end) 报废
from dm_tools_KC d left join dm_tools_project dtp on d.tools_name = dtp.tools_name where d.TOOLS_NAME =‘BH’ group by d.tools_name,dtp.specs,dtp.type;

上面这个sql就是统计出不同工具名称的各个状态的数量,按工具名称进行分组统计

sum(case when t.ride_num=1 then 1 else 0 end ) as ride_1_times

count(case when t.ride_num=1 then 1 else null end ) as ride_1_times

count(case when t.ride_num=1 then 1 end ) as ride_1_times then=1,

两者的查询结果相同,但sum 中case when de else 需要为0,而count case when 的else需要设定为null或者不写。count默认不统计null ,不能为0.

select c.MRL,c.OPERATION_ID,c.PRODUCT_ID,
sum(if(TYPE=‘ONSHOW’,1,0) as 上架数,
sum(if(TYPE=‘WITHDRAW’,1,0) as 下架数,
sum(if(TYPE=‘MOVE’,1,0) as 迁移数
from chanage_apply c,chanage_cabinets d
where c. – ??? 看不出你这两个表如何联接。
group by c.MRL,c.OPERATION_ID,c.PRODUCT_ID
写sql用sum能得出结果,但不建议用,应该用case when.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值