sql ifnull(), if(), case when then else end ,的使用

关于DQL语句的大总结:

​ select
​ …
​ from
​ …
​ where
​ …
​ group by
​ …
​ having
​ …
​ order by
​ …
​ limit
​ …
​ 执行顺序:
​ 1.from
​ 2.where
​ 3.group by
​ 4.having
​ 5.select
​ 6.order by
​ 7.limit

count()

count()函数 计算表中某个字段有多少条记录

一、IFNULL(expr1,expr2)用法

假如expr1不为NULL,则 IFNULL() 的返回值为expr1; 否则其返回值为 expr2。IFNULL()的返回值是数字或是字符串,具体情况取决于其所使用的语境。

 SELECT  IFNULL(1,0);   -- 1                       
 SELECT  IFNULL(NULL,10);  -- 10                            
 SELECT  IFNULL(1/0,10);    -- 10
 SELECT  IFNULL(1/0,'yes');   -- 'yes'  
 SELECT  IFNULL('','yes');   -- '' 
二、ISNULL(expr) 的用法

如expr 为null,那么isnull() 的返回值为 1,否则返回值为 0。

select isnull(1+1) ; -- 0
select isnull(1/0);  -- 1
三、NULLIF(expr1,expr2)用法

如果expr1 = expr2 成立,那么返回值为NULL,否则返回值为expr1。这和CASE WHEN expr1 = expr2 THEN NULL ELSE expr1 END相同。

SELECT NULLIF(1,1);    -- Null
SELECT   NULLIF(1,2);  -- 1

sql题目:

case when then else end

现在运营想要将用户划分为25岁以下和25岁及以上两个年龄段,分别查看这两个年龄段用户数量

本题注意:age为null 也记为 25岁以下

select
    if (age >= 25,  '25岁及以上' , '25岁以下') as age_cut,
    count(id)
from
    user_profile
    group by age_cut
select
    (
        case
            when age >= 25 then
            '25岁及以上'
            else '25岁以下' end
        ) as age_cut,
        count(id)
        from
            user_profile
        group by
            age_cut

经典 if()嵌套if()
SELECT device_id,gender,
  IF(age is null,'其他',
     IF(age<20,'20岁以下',
     	IF(age<=24,'20-24岁','25岁及以上'))) age_cut
FROM user_profile

常规解法
select
    device_id,
    gender,
    case
        when age >= 25 then '25岁及以上'
        when age >= 20 then '20-24岁'
        when age < 20 then '20岁以下'
        else '其他'
    end as age_cut
from
    user_profile
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值