Copy +---------------------+---------+
| Column Name | Type |
+---------------------+---------+
| session_id | int |
| duration | int |
+---------------------+---------+
session_id 是该表主键
duration 是用户访问应用的时间, 以秒为单位
你想知道用户在你的 app 上的访问时长情况。因此决定统计访问时长区间分别为 "[0-5>", "[5-10>", "[10-15>" 和 "15 or more" (单位:分钟)的会话数量,并以此绘制柱状图。
Copy Sessions 表:
+-------------+---------------+
| session_id | duration |
+-------------+---------------+
| 1 | 30 |
| 2 | 199 |
| 3 | 299 |
| 4 | 580 |
| 5 | 1000 |
+-------------+---------------+
Result 表:
+--------------+--------------+
| bin | total |
+--------------+--------------+
| [0-5> | 3 |
| [5-10> | 1 |
| [10-15> | 0 |
| 15 or more | 1 |
+--------------+--------------+
对于 session_id 1,2 和 3 ,它们的访问时间大于等于 0 分钟且小于 5 分钟。
对于 session_id 4,它的访问时间大于等于 5 分钟且小于 10 分钟。
没有会话的访问时间大于等于 10 分钟且小于 15 分钟。
对于 session_id 5, 它的访问时间大于等于 15 分钟。
Copy with
t as
( select session_id,
case when duration / 60 >= 0 and duration / 60 < 5 then '[0-5>'
when duration / 60 < 10 then '[5-10>'
when duration / 60 < 15 then '[10-15>'
else '15 or more' end as bin
from Sessions ),
b as
( SELECT "[0-5>" as bin union
SELECT "[5-10>" union
SELECT "[10-15>" union
SELECT "15 or more" )
select b.bin, count (t.bin) total
from b left join t on b.bin = t.bin GROUP BY b.bin;
Copy Create table If Not Exists Sessions (session_id int , duration int );
Truncate table Sessions ;
insert into Sessions (session_id, duration) values ( '1' , '30' );
insert into Sessions (session_id, duration) values ( '2' , '199' );
insert into Sessions (session_id, duration) values ( '3' , '299' );
insert into Sessions (session_id, duration) values ( '4' , '580' );
insert into Sessions (session_id, duration) values ( '5' , '1000' );