【发布时间】:2021-12-05 18:04:39
【问题描述】:
编写 SQL 查询以报告在首次登录后的第二天再次登录的玩家比例,四舍五入到小数点后 2 位。换句话说,您需要计算从首次登录日期开始至少连续两天登录的玩家数量,然后将该数字除以玩家总数。
查询结果格式如下例。
Example 1:
Input:
Activity table:
+-----------+-----------+------------+--------------+
| player_id | device_id | event_date | games_played |
+-----------+-----------+------------+--------------+
| 1 | 2 | 2016-03-01 | 5 |
| 1 | 2 | 2016-03-02 | 6 |
| 2 | 3 | 2017-06-25 | 1 |
| 3 | 1 | 2016-03-02 | 0 |
| 3 | 4 | 2018-07-03 | 5 |
+-----------+-----------+------------+--------------+
Output:
+-----------+
| fraction |
+-----------+
| 0.33 |
+-----------+
Explanation:
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
当使用这个查询this leetcode 时,问题是通过所有测试用例:
WITH temp AS(
SELECT player_id,
event_date - LAG(event_date, 1) OVER (PARTITION BY player_id ORDER BY event_date) AS difference,
RANK() OVER (PARTITION BY player_id ORDER BY event_date) as rn
FROM activity
),
tp AS
(
SELECT count(distinct(player_id)) as all_players
FROM activity
)
SELECT ROUND(count(t.player_id)/tp.all_players,2) AS fraction
FROM temp t
JOIN tp
WHERE t.rn = 2
AND t.difference = 1
当我使用下面的查询时,它不适用于所有测试用例,谁能告诉我为什么这在上面的查询中不起作用:
WITH temp AS(
SELECT DISTINCT(player_id), difference FROM
(SELECT player_id, event_date - LAG(event_date, 1) OVER (PARTITION BY player_id ORDER BY event_date) AS difference FROM activity) x WHERE x.difference = 1
),
tp AS
(
SELECT count(distinct(player_id)) as all_players
FROM activity
)
SELECT ROUND(COUNT(*)/tp.all_players, 2) as fraction FROM temp, tp;
【问题讨论】: