SQL 中也可以使用 if 语句
当我们需要获取符合某些条件的数据时,有两种方法
需求描述:
表 table_2 中记录了用户的 ID(user_id)、每个用户看到的内容数量(exp_cnt),我们希望计算那些看过 2 篇以上内容数的用户总量有多少
- 在 where 后面设定条件
select count(distinct user_id) as '用户数'
from table_2
where exp_cnt > 2
- 在 select 的时候使用 if 语句
select count ( distinct if ( exp_cnt > 2, user_id, null ) )as '用户数'
from table_2
第二种方式相比第一种,具备同时设置多个条件的能力。第一种方式 where 后面跟随的条件,在一个字段上只能设置一个条件,第二种方式,可以在一个字段上设置多个条件,并将结果输出为一张「宽表」。
需求描述:
表 table_2 中记录了用户的 ID(user_id)、每个用户看到的内容数量(exp_cnt),我们希望计算那些看过 1 篇、2~5 篇、6 篇及以上内容数的用户总量有多少
select
count ( distinct if ( exp_cnt == 1, user_id, null ) )as '看过 1 篇的用户数',
count ( distinct if ( exp_cnt between 2 and 5, user_id, null ) )as '看过 2~5 篇的用户数',
count ( distinct if ( exp_cnt > 5, user_id, null ) )as '看过 6 篇及以上的用户数',
from table_2
这样得到的结果就会是
看过 1 篇的用户数 | 看过 2~5 篇的用户数 | 看过 6 篇及以上的用户数 |
---|---|---|
400 | 300 | 50 |
但是这种「宽表」不太利于数据分析,而且在 SQL 语句编写的时候也会变得异常复杂,所以一般会使用 case when 去导出「长表」(见 SQL 学习记录(1 / N))