【力扣白嫖日记】1435.制作会话柱状图

前言

练习sql语句,所有题目来自于力扣(https://leetcode.cn/problemset/database/)的免费数据库练习题。

今日题目:

1435.制作会话柱状图
表:Sessions

列名类型
session_idint
durationint

session_id 是该表主键,duration 是用户访问应用的时间, 以秒为单位
你想知道用户在你的 app 上的访问时长情况。因此你决定统计访问时长区间分别为 “[0-5>”,“[5-10>”,“[10-15>” 和 “15 minutes or more” 的会话数量,并以此绘制柱状图。
写一个解决方案来报告 (bin, total) 。
返回结果 无顺序要求 。


我那不值一提的想法:

  • 首先梳理表内容,题干一共给了一张会话表,记录了会话id,用户访问应用时间。
  • 其次分析需求,你想知道用户在你的 app 上的访问时长情况。因此你决定统计访问时长区间分别为 “[0-5>”,“[5-10>”,“[10-15>” 和 “15 minutes or more” 的会话数量,并以此绘制柱状图。
  • 这种逻辑判断题,一般都用case when
  • 我们首先创建bin表
  • 然后使用case when 判断每个区间的数量
  • 再用完整bin表左连接数量表
with bin_1 as(
    select "[0-5>" as bin 
    union
    select "[5-10>" as bin
    union
    select "[10-15>" as bin
    union
    select "15 or more" as bin
)
,
bin_count as (
    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,count(*) as total 
    from Sessions 
    group by bin 
)   

select b1.bin,ifnull(total,0) as total
from bin_1 b1
left join bin_count b2 
on b1.bin = b2.bin 

结果:

在这里插入图片描述


总结:

能运行就行。


  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值