关于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