SQL面试题总结

本文总结了SQL面试中涉及的各类问题,包括连续时间计算、聚合函数应用、数据排序、成绩与订单分析、留存率计算、字符拆分、员工薪资增长、工时统计、用户行为分析等。通过这些题目,可以考察SQL在处理连续签到、订单、成绩、员工信息、工时、用户留存和操作序列分析等方面的能力。
摘要由CSDN通过智能技术生成

1.表t_act_records表,包含两个字段:uid(用户ID),imp_date(日期yyyy-mm-dd) 连续时间问题

  • 1)计算2020年每个月,每个用户连续签到的最多天数
  • 2)计算2020年每个月,连续2天都有登陆的用户名单
  • 3)计算2020年每个月,连续5天都有登陆的用户数

1)计算2020年每个月,每个用户连续签到的最多天数

with temp_1 as (
	select distinct uid, imp_date
	from t_act_records
	where year(imp_date)=2020
	)
	,temp_2 as(
	select uid, imp_date,row_number()over(partition by uid,month(imp_date) order by imp_date) rank
	from temp_1
	)
	,temp_3 as(
	select uid,month(imp_date)as month,date_sub(imp_date,rank),count(1) as cnt
	from temp_2
	group by 1,2,3)
select month,uid,max(cnt)
from temp_3
group by 1,2

2)计算2020年每个月,连续2天都有登陆的用户名单

with temp_1 as (
	select distinct uid, imp_date
	from t_act_records
	where year(imp_date)=2020
	)
	,temp_2 as(
	select uid, imp_date,lead(impt_date,1) over(partiton by month(impt_date),uid order by imp_date) 第二次登陆日期
	from temp_1
	)
	,temp_3 as (
	select uid,month(impt_date),datediff(第二次登陆日期,imp_date) 差值
	from temp_2
	)
select month(imp_date),uid
from temp_3
group by 1,2
having 差值=1

方法二

with temp_1 as (
	select distinct uid, imp_date
	from t_act_records
	where year(imp_date)=2020
	)
	,temp_2 as(
	select uid, imp_date,row_number()over(partition by uid,month(imp_date) order by imp_date) rank
	from temp_1
	)
	,temp_3 as(
	select uid,month(imp_date)as month,date_sub(imp_date,rank) as diff
	from temp_2
	)
select month,uid,
from temp_3
group by 1,2
having count(diff)>2

3)计算2020年每个月,连续5天都有登陆的用户数

with temp_1 as (
	select distinct uid, imp_date
	from t_act_records
	where year(imp_date)=2020
	)
	,temp_2 as(
	select uid, imp_date,row_number()over(partition by uid,month(imp_date) order by imp_date) rank
	from temp_1
	)
	,temp_3 as(
	select uid,month(imp_date)as month,date_sub(imp_date,rank) as diff
	from temp_2
	)
select month,count(distinct uid),
from temp_3
group by 1
having count(diff)>5

–方法2

with temp_1 as (
	select distinct uid, imp_date
	from t_act_records
	where year(imp_date)=2020
	)
	,temp_2 as(
	select uid, imp_date,row_number()over(partition by uid,month(imp_date) order by imp_date) rank
	from temp_1
	)
	,temp_3 as(
	select u
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值