0

The task is to find what fraction of total users have logged in at least for one more consecutive day after their first login.

SELECT 
    ROUND( COUNT( b.player_id )/COUNT( DISTINCT (SELECT a.player_id FROM Activity a) ), 2 ) AS fraction
FROM 
    Activity b
WHERE 
    (b.player_id, DATE_ADD(b.event_date, INTERVAL -1 DAY)) IN
(
    SELECT 
        player_id, MIN(event_date)
    FROM 
        Activity
    GROUP BY 
        player_id
)```

The table structure is as follows

Table: 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            |
+-----------+-----------+------------+--------------+

I'm using two aliases a and b for the same table for referring them.

  • a is for the unfiltered table, because I need a count of all Distinct users.
  • b is for the filtered table, where only those rows are included for which a condition is met.

Where am I doing it wrong?

3
  • Some example input data and expected results would be helpful.
    – J.D.
    Commented Dec 26, 2023 at 14:27
  • 1
    What version of MySQL? This sounds like a good use case for a CTE that finds the player_id, MIN(event_date).
    – Rick James
    Commented Dec 26, 2023 at 17:08
  • @J.D. @Rick James The version is MySQL 8.0. I found out the error. I wrote COUNT( DISTINCT (SELECT a.player_id FROM Activity a) ), which doesn't make sense. It should be SELECT COUNT(DISTINCT a.player_id FROM Activity a)
    – Pixel_Bear
    Commented Dec 27, 2023 at 19:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.