LeetCode刷题-数据库(MySQL)-550. Game Play Analysis IV

这篇博客探讨了LeetCode第550题——Game Play Analysis IV的解决方案。内容包括问题描述、思路分析和SQL查询实现。题目要求计算首次登录后次日再次登录的玩家比例,结果需要四舍五入到小数点后两位。文章详细解释了如何计算这个比例,重点在于找出连续两天登录的玩家并计算其占比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

550. Game Play Analysis IV

一、题目描述

Table: Activity

Column NameType
player_idint
device_idint
event_datedate
games_playedint

(player_id, event_date) is the primary key of this table.
This table shows the activity of players of some game.
Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on some day using some device.

Write an SQL query that reports the fraction of players that logged in again on the day after the day they first logged in, rounded to 2 decimal places. In other words, you need to count the number of players that logged in for at least two consecutive days starting from their first login date, then divide that number by the total number of players.

The query result format is in the following example:

Activity table:

player_iddevice_idevent_dategames_played
122016-03-015
122016-03-026
232017-06-251
312016-03-020
342018-07-035

Result table:

fraction
0.33

Only the player with id 1 logged back in after the first day he had logged in so the answer is 1/3 = 0.33

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/game-play-analysis-iv
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、思路分析

Write an SQL query that reports the fraction of players that logged in again on the day after the day they first logged in, rounded to 2 decimal places. In other words, you need to count the number of players that logged in for at least two consecutive days starting from their first login date, then divide that number by the total number of players.
本题要求计算一个比值,分母是所有不同选手的数量,分子是那些首次在设备登录后连续第二天又登录的选手数量。

分母很容易求,难点在于分子的计算。要计算分子,首先要找到每个选手的首次登录日期。然后,将该查询作为一个临时表与原表连接,再筛选出那些登录日期与首次登录日期相差一天的记录,最后计算数量即可。

三、代码实现

SELECT ROUND
	(
		(
			SELECT 
				COUNT(
					IF(DATEDIFF(a1.event_date, a2.min_date) = 1, 1, null)
					)
			FROM
				Activity a1,
				(
					SELECT
						player_id,
						MIN(event_date) AS min_date
					FROM
						Activity
					GROUP BY player_id
				) a2
			WHERE
				a1.player_id = a2.player_id
		) 
		/ COUNT(DISTINCT(player_id))	
, 2) fraction
FROM
	Activity
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值