【问题标题】:Window function query issue?窗口函数查询问题?
【发布时间】: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;

【问题讨论】:

    标签: mysql window-functions


    【解决方案1】:

    仅在他们的第二次登录是连续的情况下才要求您计算。第一个查询通过仅计算相差 1 的第二行来完成此操作。

    WHERE t.rn = 2
    AND t.difference = 1
    

    第二个查询将需要任何连续登录。

    Demonstration


    请注意,两个查询都需要group by tp.all_players。在某些模式下,MySQL 有时会为您推断组依据。但不要指望它,其他数据库不会。见MySQL Handling of GROUP BY。考虑在ANSI mode 中运行 MySQL,同时学习 SQL 以使其更好地遵循标准。

    【讨论】:

      猜你喜欢
      • 2023-02-23
      • 2021-07-09
      • 2014-03-10
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-05
      相关资源
      最近更新 更多