面试SQL题 计算每年在校生人数

**题目均来自社区同学遇到面试题**

有一个录取学生人数表,记录的是每年录取学生人数和入学学生的学制,然后计算每年在校生人数

with data as (
--             主键        入学年份            人数            学制
    select 1 as id , 2001 as year , 1200 as stu_num , '3' as stu_len union all
    select 2 as id , 2000 as year , 1300 as stu_num , '5' as stu_len union all
    select 3 as id , 2003 as year , 1400 as stu_num , '4' as stu_len union all
    select 4 as id , 2002 as year , 1500 as stu_num , '3' as stu_len union all
    select 5 as id , 2002 as year , 1600 as stu_num , '2' as stu_len
)
select
  year,
  sum(stu_num) -- 聚合在校生
from
  (
    select
      id,
      (year + pos) as year, 
      stu_num,
      stu_len,
      val
    from
      data 
    lateral view 
        posexplode(
            split(space( cast(stu_len as int) ) , '(?!$)' ) --产生学制数个空格并切割
            --split(space( cast(stu_len as int) - 1 ) , ' ' ) --不用正则的写法,效果同上
        ) -- posexplode 炸裂函数 返回带下标的表
        t as pos,val -- posexplode 炸裂函数 返回 下标和具体值
  ) t -- 派生表别名
group by
  year -- 按照年份分组,聚合在校生

答案如下

炸裂函数是面试常考的知识点,也是区分候选人SQL思维高低的好办法,建议熟练掌握

更多实战题目和解法思路尽在社区,还有视频讲解哦

#数据人的面试交流地##SQL面试#
全部评论

相关推荐

昨天 10:08
门头沟学院 C++
北京Golang实习,一个月4700,吃住都不报,公司位置在海淀。请问友友怎么看呢?如果要租房的话有什么建议吗
码农索隆:租房肯定是合租了,剩下的钱,差不多够正常吃饭了,看看能不能学到东西吧
点赞 评论 收藏
分享
缒梦&独舞:这家公司是这样的,去年给我实习offer了,不过也是面着玩儿的,他周六还要去做公益志愿活动
点赞 评论 收藏
分享
每晚夜里独自颤抖:这个在牛客不是老熟人了吗
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-24 14:18
点赞 评论 收藏
分享
评论
2
6
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务