문제
Write a solution to report 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.
처음 로그인 후 다시 로그인 한 플레이어의 비율을 소수점 이하 2자리로 반올림하시오.
다시말해 플레이어의 수를 세야하는데, 첫 로그인 일자로부터 최소 2일 연속으로 로그인한 플레이어 수를 계한한 다음 전체 플레이어 수로 나누어야한다.
테이블 & 예제
[Activity]
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| player_id | int |
| device_id | int |
| event_date | date |
| games_played | int |
+--------------+---------+
[예제]
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 |
+-----------+
풀이
풀이 방법을 조금 찾아서 진행했다.
datediff를 수행함에 있어서 센스가 조금 모자라서 값이 다르게 나왔는데 처음에는 LEAD를 사용해서 값을 비교했었다.
그런데 min을 사용해서 비교하니까 확실히 편해지는 경험을 할 수 있었다.
서브쿼리를 이용해서 진행하였다.
각 플레이어에 대해서 최소 이벤트날짜와의 차이가 1인 경우를 카운트해서 최초 로그인 후 연속2일 접속을 확인한다.
후에 SUM과 기존 플레이어의 수를 구해서 나누는 작업으로 결과를 도출했다.
WITH a1 AS (
SELECT
player_id,
CASE WHEN datediff(event_date,min(event_date) over (PARTITION BY player_id)) = 1 THEN 1 ELSE 0 END AS temp
FROM Activity
)
SELECT
ROUND (SUM(temp)/COUNT(DISTINCT player_id),2) AS fraction
FROM a1;
'코딩테스트 > SQL' 카테고리의 다른 글
SQL > LeetCode 619. Biggest Single Number (MySQL) (0) | 2024.06.07 |
---|---|
SQL > LeetCode 1070. Product Sales Analysis III (MySQL) (0) | 2024.06.06 |
SQL > LeetCode 1193. Monthly Transactions I (MySQL) (2) | 2024.06.02 |
SQL > LeetCode 1633. Percentage of Users Attended a Contest(MySQL) (1) | 2024.05.29 |
SQL > LeetCode 1251. Average Selling Price (MySQL) (0) | 2024.05.28 |