题目:
需求:编写一个 SQL 查询,报告在首次登录的第二天再次登录的玩家的分数,四舍五入到小数点后两位。换句话说,您需要计算从首次登录日期开始至少连续两天登录的玩家的数量,然后除以玩家总数。
查询结果格式如下所示:
解题思路:
①先将登录日期上移一行,方便筛选出连续登录数;
1 SELECT 2 player_id, 3 event_date, 4 lead ( event_date, 1 ) over (partition by player_id ORDER BY event_date ) AS after_date 5 FROM activity;
②筛选出连续两天登录的用户数;
1 SELECT count( * ) AS nums1 2 FROM ( 3 SELECT 4 player_id, 5 event_date, 6 lead ( event_date, 1 ) over (partition by player_id ORDER BY event_date ) AS after_date 7 FROM activity ) AS temp 8 WHERE datediff(after_date, event_date ) = 1;
③求出玩家总数,注意去重;
1 SELECT count( DISTINCT player_id ) AS total_num 2 FROM activity;
④使用笛卡尔积拼接一下,计算结果。
方法二:
①先求出所有玩家的第一次登录时间
1 SELECT 2 player_id, 3 MIN(event_date) AS first_date 4 FROM Activity 5 GROUP BY player_id;
②将原表与第一步求出来的临时表进行左连接;
1 select * 2 from activity a 3 left join (SELECT 4 player_id, 5 MIN(event_date) AS first_date 6 FROM Activity 7 GROUP BY player_id) as b 8 on a.player_id = b.player_id and datediff(event_date,first_date) = 1;
③统计出左右两个表的数量,进行计算;
小知识:
①lead() over:
1.点击这里可以看语法
②左右内连接:跳转这里看笔记
标签:登录,550,event,力扣,player,MySQL,date,id,SELECT From: https://www.cnblogs.com/liu-myu/p/17243259.html