sql case when 多条件 小结

博客介绍了数据库中Case函数的两种格式。一是简单Case函数,给出格式说明并配有示例;二是Case搜索函数,同样有格式说明和示例,通过示例展示了如何根据不同条件返回不同结果,适用于数据库查询操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

--  第一种 格式 : 简单Case函数 :
-- 格式说明    
--     case 列名
--     when   条件值1   then  选择项1
--     when   条件值2    then  选项2.......
--     else     默认值      end

--例子:
SELECT
    `cus`.`cus_name`,
    `cus`.`company_name`,
    `cus`.`reg_mobile`,
    `r`.`region_name`,
    CASE `cus`.`cus_statu`
WHEN 0 THEN
    '待审核'
WHEN 1 THEN
    '正常'
ELSE
    '冻结'
END
FROM
    `customer` `cus`
LEFT JOIN `region` `r` ON `r`.`region_id` = `cus`.`proid`
WHERE
    `cus`.`pro` IN (
        '浙江',
        '江苏',
        '安徽',
        '江西',
        '福建',
        '上海'
    )

 

--  第2种 格式 : Case搜索函数 :

-- 格式说明    
--     case 列名
--     when   字段 = 条件值1   then  选择项1
--     when   字段 = 条件值2    then  选项2.......
--     else   字段 = 默认值      end
--        as     字段
--例子:
SELECT
    `cus`.`cus_name`,
    `cus`.`company_name`,
    `cus`.`reg_mobile`,
    `r`.`region_name`,
  `cus`.`cus_statu`,
     case 
        when `cus`.`cus_statu` = 0 then '待审核'
        when `cus`.`cus_statu` = 1 then '正常'
        else  '冻结' end
   as cus_statu_name     
   
FROM
    `customer` `cus`
LEFT JOIN `region` `r` ON `r`.`region_id` = `cus`.`proid`
WHERE
    `cus`.`pro` IN (
        '浙江',
        '江苏',
        '安徽',
        '江西',
        '福建',
        '上海'
    )

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值