表:Sessions+---------------------+---------+| Column Name | Type |+---------------------+---------+| session_id | int || duration | int |+---------------------+---------+session_id 是该表主键duration 是用户访问应用的时间, 以秒为单位你想知道用户在你的 app 上的访问时长情况。因此决定统计访问时长区间分别为 "[0-5>", "[5-10>", "[10-15>"和"15 or more" (单位:分钟)的会话数量,并以此绘制柱状图。写一个SQL查询来报告(访问时长区间,会话总数)。结果可用任何顺序呈现。下方为查询的输出格式: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 分钟。来源:力扣(LeetCode)链接:https://leetcode.cn/problems/create-a-session-bar-chart
#测试数据Create table If Not Exists Sessions (session_id int, duration int);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');
withtmp as (select '[0-5>' as bin unionselect '[5-10>' as bin unionselect '[10-15>' as bin unionselect '15 or more' as bin)selecta.bin,coalesce(b.total,0) totalfrom tmp aleft join (selectcase when 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 bin,count(1) totalfrom Sessionsgroup by 1)bon a.bin = b.bin;

笔试题合集免费领取方法
方法一:关注公众号【跟强哥学SQL】,回复关键字【力扣】获取链接。
方法二:访问【SQL网】:https://sql.wang/sql-leetcode/sql-exercise
文章转载自跟强哥学SQL,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




