一个表table: c_id u_id score;用SQL计算每个班级top5学生的平均分(腾讯)
select class_id
,avg(score) as score_avg
from
(select *
,row_number() over(partition by class_id order by score desc) as score_rank
from table
) t1
where t1.score_rank<=5
gropu by t1.class_id
计算连续登陆3天的用户?营业额连续增长的店铺?(腾讯、零食有鸣)
--原始数据
u_1 2024-08-01
u_1 2024-08-02
u_1 2024-08-03
u_1 2024-08-05
u_1 2024-08-06
u_2 2024-08-01
u_2 2024-08-03
--lag() over()函数+dadedif
lag(date,1) diff_1 lag(date,2). diff_2
u_1 2024-08-01 null null null null
u_1 2024-08-02 2024-08-01 1 null null
u_1 2024-08-03 2024-08-02 1 2024-08-01 1
u_1 2024-08-05 2024-08-03 2 2024-08-02 1
u_1 2024-08-06 2024-08-05 1 2024-08-03 2
u_2 2024-08-01 null 1 null null
u_2 2024-08-03 2024-08-01 2 null null
select distinct user_id
from table
where lag(date,1) is not null
and diff_1=1
and diff_2=1
腾讯SQL手写笔试题目
1.
先会有登陆事件、再有对局事件
login_log表作为left join的主表
一个玩家登陆之后,可能会对应多次对局
对局时间大于最近一次登陆时间:每一个对局时间,对应多个登陆时间,找到最晚的那一个就可以了
select t1.uid
,t2.battle_time
,max(login_time) as login_time
from login_log t1
left join battle_log t2
on t1.uid=t2.uid
and t1.login_time<t2.battle_time
group by t1.uid
,t2.battle_time
2.
首先进行split切分操作
其次进行行转列操作,将数据打散
最后按照兴趣聚合
select hobby_new_1
,count(name) as user_cnt
from
(
select t1.name
,t2.hobby_new_1
from
(select name
,split(hobby,'+') as hobby_new
from hobby_detail
) t1
lateral view explode(t1.hobby_new) hobby_new_1 as t2
) t
group by hobby_new_1
腾讯SQL手写笔试题目
问题1
引擎:hive/spark
语句:
select stu_id
from scoce_detail
group by stu_id
having min(score) > 60;
思路:在scoce_detail表中,每一个学生最小的成绩只要大于60分,那么其他科目都满足条件,该学生就是目标学生(前提是学生某些科目没有成绩,不做过滤)
问题2
引擎:hive/spark
语句:
select t.stu_id
from
(select stu_id
,count(if(subject='数学',1,null)) as math_subject_cnt
from score_detail
group by stu_id
having(count(if(subject='数学',1,null)))<1
) t ;
思路:统计每个学生下的 数学科目的条数,如果数学科目条数小于1,代表该学生没有数据成绩