自定义区间统计频数

你想知道用户在你的 app 上的访问时长情况。因此决定统计访问时长区间分别为 "[0-5>", "[5-10>", "[10-15>" 和 "15 or more" (单位:分钟)的会话数量,并以此绘制柱状图。

写一个SQL查询来报告(访问时长区间,会话总数)。结果可用任何顺序呈现。

方法一:用union连接 

select '[0-5>' as bin,
       count(*) as total 
from Sessions s
where s.duration/60 >= 0 and s.duration/60 < 5

union
select '[5-10>' as bin,
       count(*) as total 
from Sessions s
where s.duration/60 >= 5 and s.duration/60 < 10

union
select '[10-15>' as bin,
       count(*) as total 
from Sessions s 
where s.duration/60 >= 10 and s.duration/60 < 15

union
select '15 or more' as bin,
       count(*) as total 
from Sessions s 
where s.duration/60 >= 15

方法二:case when :

select
(case when duration/60 >= 0 and duration/60 < 5 then '[0,5>'
when duration/60 >= 5 and duration/60 < 10 then '[5,10>'
when duration/60 >= 10 and duration/60 < 15 then '[10,15>'
else '15 or more'
end) as bins, count(duration) as total
from Sessions
group by bins
order by bins;

这种会只有三个结果,因为group by会将频数为0的结果不显示,所以需要改进为如下SQL:

含有GROUP BY子句的查询中如何显示COUNT()为0的结果

select t1.bin, ifnull(count(t2.bin),0) as total
from(
    select '[0-5>' as bin union all select '[5-10>' as bin union all
    select '[10-15>' as bin union all select '15 or more' as bin)t1
left join
(select case when duration >= 0 and duration < 300 then '[0-5>'
             when duration >= 300 and duration < 600 then '[5-10>'
             when duration >= 600 and duration < 900 then '[10-15>'
             else '15 or more' end as bin from Sessions)t2
on t1.bin = t2.bin
group by t1.bin

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值