sql面试题

user登陆表数据如下,求出连续登录3天及以上的用户
sql面试题_第1张图片
方法1:排序,dt列求出本行和前面第2行的日期差,等于2则三天连续

SELECT DISTINCT uid
FROM
(SELECT uid,dt,lag(dt,2) over(PARTITION BY uid ORDER BY dt) AS lag_dt
FROM USER
)aa WHERE DATEDIFF(dt,lag_dt)=2

方法2:排序,dt减去排序序号的日期差相等的数量大于等于3 (推荐!!!

SELECT uid
FROM
(
	SELECT uid,dt,rn,DATE_SUB(dt,INTERVAL rn DAY) AS diff
	FROM
	(SELECT uid,dt,row_number() over(PARTITION BY uid ORDER BY dt) AS rn FROM USER)aa
)bb
GROUP BY uid,diff HAVING COUNT(1)>=3

你可能感兴趣的:(工作,sql,数据库)